Reputation: 356
been struggling with this one what im trying to do is create a second hidden input field from the text in first depending on what is selected this is what ive tried:
<script>
var $extraval = $('#citycode option:selected').text();
var input = $("<input>").attr("type", "hidden").attr("name", "city").val("$extraval");
$('#form').append($(input));
</script>
this is what the first select looks like
<select id="citycode" name="citycode">
<option value="3439389">Asuncion</option>
<option value="3439352">Bella Vista</option>
<option value="3439101">Ciudad Del Este</option>
<option value="3438735">Encarnacion</option>
</select>
so basically what im trying to do is create a second hidden form input with the text of this select when submited as the value of the input
Upvotes: 1
Views: 3662
Reputation: 356
ok so thanks for all the help everyone this is how i got it working
<script>
$('#form').submit(function() {
var extraval = $('#citycode option:selected').text();
var $input = $("<input>", {
'type': 'hidden',
'name': 'city',
'value': extraval
});
$('#form').append($input);
});
</script>
placed at the end of the form works great
Upvotes: 0
Reputation: 26320
Assuming that it's inside #form
, I found two errors:
"
when you try to set input
value passing $extraval
as parameter..append(input)
Try the following:
var extraval = $('#citycode option:selected').text();
var $input = $("<input>", {
'type': 'hidden',
'name': 'city',
'value': extraval
});
$('#form').append($input);
Upvotes: 3
Reputation: 2377
http://jsfiddle.net/pWkDR/.. This is what you should do
CODE:
var $extraval = "yourtext";
var input = $("<input>").attr("type", "hidden").attr("name", "city").val($extraval);
$('body').append(input);
// check in inspect element your hidden field is there with data
Upvotes: 2
Reputation: 786
<script>
var extraval = $('#citycode option:selected').text();
var input = $("<input>").attr("type", "hidden").attr("name", "city").val(extraval);
$('#form').append($(input));
</script>
try this code
Upvotes: 2
Reputation: 78671
Write .val($extraval)
instead of .val("$extraval")
. This is not PHP.
jsFiddle Demo (creates a text input instead of hidden - for visibility purposes)
Also, the selector '#form'
expects a form in your code having the id form
. You can get the form that the select
is a part of by using one of these:
$('#citycode').closest('form').append(input);
or
input.appendTo($('#citycode').prop('form'));
Upvotes: 2