0

I've got option select. How to set as var selected select automaticly?

<option>
<select>1</select>
<select>2</select>
</option>

E.g. I manually select option 1, and it automaticly is

<select selected="selected">1</select>

EDIT I found out.

<select id="sel">
    <option value="1">aa</option>
    <option value="2">bb</option>
    <option value="3">cc</option>
</select>

$("#sel").change(function(){
   alert($(this).val())
});
beetle
  • 195
  • 2
  • 4
  • 11
  • 4
    I don't understand your problem exactly, but you got it wrong. `select` is the outside tag, and inside should be `option`s. – kapa Apr 11 '12 at 08:17
  • Didn't even notice that, that's right, your code is messed up! – elclanrs Apr 11 '12 at 08:19
  • think you need to clarify what is it you want to do! – Joe Apr 11 '12 at 08:39
  • "User can choose "2" and option "2" have to automaticly set to 'selected'", quoting you, this happens already, whichever option you select, is the value "selected" when the form is submitted. – Joe Apr 11 '12 at 08:41

4 Answers4

1

try this

$("#myOption").val("1");
Willem D'Haeseleer
  • 18,763
  • 7
  • 60
  • 96
  • I've got form and I need to automaticly pass the data. User can choose "2" and option "2" have to automaticly set to "selected" – beetle Apr 11 '12 at 08:20
1

your code should be

<select>
    <option selected="selected">1</option>
    <option>2</option>
</select>
ncremins
  • 9,050
  • 2
  • 23
  • 24
  • Yes - but I need this to set automaticly when i select it. I've got form. I need to pass value by ajax. – beetle Apr 11 '12 at 08:22
  • then use the jQuery mentioned in other answers $("#myOption").val("1"); wrap it in a $(document).ready() – ncremins Apr 11 '12 at 08:46
0

I agree with @creminsn!! and For that to get value Try this

var val;
$('#selectID').click(function(){
val=$('#selectID option:selected').val();
});

val will give you the selected val.And if you need text you can do

$('#selectID option:selected').text();
mesimplybj
  • 629
  • 1
  • 5
  • 27
0

I don't quite see what your issue is, however im getting the idea from what you've written that you want to submit the form upon the user selecting an option from the dropdown?

In which case u need JQuery to implement a listener (.live()) on the dropdown which will fire an event, in your case you want to submit the form (i think) so perhaps use .post() if you do want to use ajax.

look these up on the jQuery site.

Joe
  • 2,590
  • 5
  • 34
  • 48