tags:

views:

186

answers:

4

if i have a form with the following two elements.

<select name="" size="5" id="reasons" multiple="multiple">
    <option value="1">test1*</option>
    <option value="2">test2*</option>
    <option value="3">test3*</option>
    <option value="4">test4</option>
    <option value="5">test5</option>
</select>
<input type="checkbox" name="somecheckbox" id="checkboxId"/>

In the select box the users can select multiple things. Upon submit how can I check if the user has selected one of the options with '*' in the end and if they have then automatically checkmark the checkbox?

Is there a way to do this in jQuery?

A: 

In plain javascript you'd do something like this:

var sel = document.getElementById('reasons');

for (var i = 0, l = sel.options.length; i < l; ++i) {
    if (sel.options[i].selected && sel.options[i].innerHTML.match(/\*/)) {
        document.getElementById('checkboxId').checked = true;
        break;
    }
}
nickf
A: 

Is there a reason you wouldn't update 'checkboxId' onchange of 'reasons' select? (As opposed to on submit)

jimyshock
+2  A: 

You can accomplish this with jQuery by doing the following:

var hasStar = ($('#reasons option:selected:contains(*)').length > 0);

Basically you're selecting on all selected <option> tags contained by your <select id="reasons"> whose text contains *.

Ken Browning
@Eric - I like nickf's answer, but *if* you're using jQuery anyway, why would you not attempt this one-liner?
karim79
A: 

I would suggest that you bind this to both your <select> and your <form>:

$(document).ready(function() {
  var selectHandler = function() {
    if ( this.options[this.selectedIndex].innerHTML.match(/\*$/) ) {
      $("#checkboxId").checked = true;
    }
  };

  $("#reasons").bind("change keypress", selectHandler);
  $("#whatever-form").bind("submit", selectHandler);
});
Justin Johnson