javascript/jquery generate input element

43,278

Solution 1

Judging by tags of your question you're using jQuery. So adding an input is fairly easy.

$("select[name=amount]").change(function() {
    if ($(this).val() == 'Other') {
        $("#custom_price").append('<input type="text" name="amount"/>');
    }
})

Solution 2

Best way would be to actually make the dom element.

var newInput = document.createElement("input");
newInput.type="text";
newInput.name="amount";
document.getElementById('custom_price').appendChild(newInput);

Perhaps with a handler like this:

assign your select an id: <select name="amount" id="amount">

$("#amount").change( function() {
 if( $(this).val() == "Other" ){
  document.getElementById('custom_price').innerHTML = "";
  var newInput = document.createElement("input");
  newInput.type="text";
  newInput.name="amount";
  document.getElementById('custom_price').appendChild(newInput);
 }
});

Solution 3

It's

document.getElementById('custom_price').innerHTML += '<input type="text" name="amount" />';

If you start a sring using ", you have to scape the caracters " inside it (\") or use '

Share:
43,278
inrob
Author by

inrob

Updated on August 15, 2020

Comments

  • inrob
    inrob over 3 years

    So I have this code. And I want to accomplish something probably simple for javascript guys. If a certain option is selected then add an input field on a div.

    <select name="amount" >
        <option value="50">50$</option>
        <option value="100">100$</option>
        <option value="Other">Other</option>
    </select>
    
    <div id="custom_price">
    
    </div>
    

    So I want to add the input field once the 'Other' option is selected. I know there's a simple way around this but I cannot make it work:

    document.getElementById('custom_price').innerHTML += "<input type="text" name="amount"/>"
    

    So custom_div would look like:

    <div id="custom_price">
    Custom price:<br>
    <input type="text" name="amount"/>
    </div>