inrob
inrob

Reputation: 5089

javascript/jquery generate input element

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>

Upvotes: 2

Views: 44833

Answers (5)

WTK
WTK

Reputation: 16961

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"/>');
    }
})

Upvotes: 3

Oriol
Oriol

Reputation: 288000

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 '

Upvotes: 1

Slava Fomin II
Slava Fomin II

Reputation: 28611

Just place the input inside of a div and hide div initially. Then use jQuery/JS to show this div when necessary.

$('select[name="amount"]').change(function() {
    if($(this).val() == 'Other') {
        $('#custom_price').show();
    } else {
        $('#custom_price').hide();
    }
});

<div id="custom_price" style="display: none;">
    <p>Custom price:</p>
    <input type="text" name="amount"/>
</div>

Upvotes: 0

Diode
Diode

Reputation: 25135

Using jQuery

$("#custom_price").empty().append('Custom price:<br><input type="text" name="amount"/>')

Upvotes: 0

Travis J
Travis J

Reputation: 82267

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);
 }
});

Upvotes: 6

Related Questions