Shortening jQuery Code by Replacing Variable

Posted by Jerry on Stack Overflow See other posts from Stack Overflow or by Jerry
Published on 2012-10-27T04:35:58Z Indexed on 2012/10/27 5:01 UTC
Read the original article Hit count: 284

Filed under:

I have a form with a bunch of dropdown options that I'm dressing up by allowing the option to be selected by clicking links and (in the future, images) instead of using the actual dropdown. There are a lot of dropdowns and most all will repeat the same basic idea, and some will literally repeat just with different variables. Here's the HTML for one of those.

<tr class="box1">
  <td>
    <select id="cimy_uef_7">
      <option value="Boy">Boy</option>
      <option value="Girl">Girl</option>
    </select>
  </td>
</tr>

Then the corresponding fancier links to click that will select the corresponding option in the dropdown.

<div id="genderBox1">
  <div class="gender"><a class="boy" href="">Boy</a></div>
  <div class="gender"><a class="girl" href="">Girl</a></div>
</div>

So, when you click the link "Boy" it will select the corresponding dropdown value "Boy" There are going to be multiple Box#, so I can just repeat the jQuery each time with the new variables, but there's surely a shorter way. Here's the jQuery that makes it work.

//Box1 Gender
  var Gender1 = $('select#cimy_uef_7');
  var Boy1 = $("#genderBox1 .gender a.boy");
  var Girl1 = $("#genderBox1 .gender a.girl");

//On Page Load - Check Gender Box 1 Selection and addClass to corresponding div a
  if ( $(Gender1).val() == "Boy" ) {
    $(Boy1).addClass("selected");
    } else {
    $(Boy1).removeClass("selected");
    }

  if ( $(Gender1).val() == "Girl" ) {
    $(Girl1).addClass("selected");
    } else {
    $(Girl1).removeClass("selected");
    }

  //On Click - Change Gender Box 1 select based on image click
  $(Boy1).click(function(event) {
    event.preventDefault();
    $(this).addClass("selected");
    $(Gender1).val("Boy");
    $(Girl1).removeClass("selected");
  });

  $(Girl1).click(function(event) {
    event.preventDefault();
    $(this).addClass("selected");
    $(Gender1).val("Girl");
    $(Boy1).removeClass("selected");
  });

My thought for shortening it was to just have a list of variables for each box and cycle through the numbers- 1,2,3,4 and have the jQuery grab the same # for each variable, but I can't figure out a way to do it.

Let me know if there's anything else I can provide to make the question better. This is my best idea for shortening this code, as I'm still very much a beginner at jQuery, but I'm positive there are much better ideas out there, so feel free to recommend a better path if you see it :)

© Stack Overflow or respective owner

Related posts about jQuery