dom
dom

Reputation: 356

how to append a hidden input with the text of another input

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

Answers (5)

dom
dom

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

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

Assuming that it's inside #form, I found two errors:

  • You don't have to use " when you try to set input value passing $extraval as parameter.
  • input is already a jQuery object, so to append it you have to do the following: .append(input)

Try the following:

var extraval = $('#citycode option:selected').text();
var $input = $("<input>", {
    'type': 'hidden',
    'name': 'city',
    'value': extraval
});
$('#form').append($input);

demo

Upvotes: 3

Ashirvad
Ashirvad

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

Param Veer
Param Veer

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

kapa
kapa

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

Related Questions