3

In my Javascript application, I receive a line of HTML code from an endpoint. I cannot change the HTML content that I receive from this endpoint. I want to convert the radio buttons into a regular button, and not sure how to go about rewriting this. The HTML I receive can have anything in it - I only want to replace the radio buttons.

Here's what I might be given as a string:

<form>
    <input type="radio" name="a" value="1">Option 1
    <br>
    <input type="radio" name="a" value="2">Option 2
</form>

and I want to convert it to this string:

<form>
    <input type="button" id="button-a-1" value="Option 1">
    <br>
    <input type="button" id="button-a-2" value="Option 2">
</form>

Here's how this is currently used:

$.post('url', data, function(resp) { $('#content').html(resp.html); });

I thought I could do this by find/replace type="radio" with type="button", but I'm not sure how to get the text after the input tag into a value tag by manipulating the string. And also get an id in there so I can tie an event handler to it.

1
  • 1
    Option 1 part is what makes this a pain.... lol Commented Aug 22, 2019 at 15:33

4 Answers 4

2

It is easier to do it with the DOM and not working with the strings. Create it as a fragement, select the elements, and replace them.

const responseText = `
<form>
    <input type="radio" name="a" value="1">Option 1
    <br>
    <input type="radio" name="a" value="2">Option 2
</form>
`
// create temp element and set the html to it
var temp = document.createElement('div')
temp.innerHTML = responseText
// find the radio buttons
var radios = temp.querySelectorAll('input[type="radio"]')
// loop over each one so we can convert it
radios.forEach(function (rb) {
  // create a button
  const button = document.createElement('input')
  button.type = 'button'
  // set the id with the radio button attributes
  button.id = `button-${rb.name}-${rb.value}` // = `button-' + rb.name + '-' + rb.value'
  // read the next sibling's text and set the value to 
  button.value = rb.nextSibling.nodeValue.trim()
  // remove the text node
  rb.nextSibling.remove()
  // replace the radio button with your new button
  rb.replaceWith(button)
});

console.log(temp.innerHTML)

Sign up to request clarification or add additional context in comments.

2 Comments

mine is easier :)
Do you want a cookie @G.aziz??? And what you did probably will fail with real world data.
1

Get the text node which is immediately after the radio, then generate the button based on the textnode content and replace the radio button with genrated button.

let html = `<form>
    <input type="radio" name="a" value="1">Option 1
    <br>
    <input type="radio" name="a" value="2">Option 2
</form>`;

// create jQuery object from html content
let $html = $(html);

$html
// filter out all the radio buttons
.find(':radio')
// use replaceWith to iterate and replace with returned element
.replaceWith(function() {
// get the text node which is immediately after the radio
  let textNode = this.nextSibling;
  // get its textcontent
  this.value =
  // remove text node
    textNode.remove();
    // generate button and return
  return $('<input>', {
    type: 'button',
    id: `button-${this.name}-${this.value}`,
    value: textNode.nodeValue.trim()
  })
})

$('#content').html($html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content"></div>


Or alternately you can modify the existing input element without creating new.

let html = `<form>
    <input type="radio" name="a" value="1">Option 1
    <br>
    <input type="radio" name="a" value="2">Option 2
</form>`;

// create jQuery object from html content
let $html = $(html);

$html
  // filter out all the radio buttons
  .find(':radio')
  // iterate and update the element
  .each(function() {
    // get the text node which is immediately after the radio
    let textNode = this.nextSibling;
    // get its textcontent
    this.value =
      // remove text node
      textNode.remove();

    // change properties

    this.type = 'button';
    this.id = `button-${this.name}-${this.value}`;
    this.value = textNode.nodeValue.trim();

  })

$('#content').html($html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content"></div>

2 Comments

I implemented this approach and it's working! How would I go about assigning a click event handler to this new button?
@GregSenne : $('<input>', { .... }).click(function(){ /*your handler code here */ })
0

use the jQuery .attr() function

$("input").attr('type', 'button');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
    <input type="radio" name="a" value="1">Option 1
    <br>
    <input type="radio" name="a" value="2">Option 2
</form>

1 Comment

and what about the id and the value:?
0

You can do it like that using only javascript

const form = document.querySelector("form");
const inputs = document.querySelectorAll("input");

inputs.forEach((input, index) => {

  input.setAttribute("type", "button")
  input.setAttribute("value", `option ${index +1}`)
  input.setAttribute("id", `button-${input.getAttribute("name")}-${index+1}`)

})

form.innerHTML = form.innerHTML.replace(/Option\s[1-9]/g, "")

console.log(form.innerHTML)
<form>
  <input type="radio" name="a" value="1">Option 1
  <br>
  <input type="radio" name="a" value="2">Option 2
</form>

3 Comments

and what about the id and the value:?
sorry what are you talking about ?
<input type="button" id="button-a-1" value="Option 1"> is supposed to be the final outcome. Your solution is not close. <input type="button" name="a" value="1">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.