Bjaeg Bjaeg - 5 months ago 9
jQuery Question

jQuery advanced select detecting and click

I have multiple li's that contain a form.

In the form I have a select with a few options in a drop down menu.

I want to create a jquery script so that if you click submit AND the select has been changed from the default (selected) option, then hide the li. The li's have unique id's.

Example code :

<li id="<?php echo 'li_'.$unique ?>">
<form id="<?php echo 'form_'.$unique ?>">
<select id="<?php echo 'select_'.$unique ?>">
<option value='apple' selected>Default</option>
<option value='pear'>Different</option
</select>
<input type="submit" id="<?php echo 'submit_'.$unique ?>"/>
</form>
</li>


What I want to achieve here..

// Script -> On .click submit and if selector != selected .hide this <li>

$("<?php echo '#submit_'.$unique ?>").click(function(){
$("<?php echo '#select_'.$unique ?>").change(function() {
if ($(this).val() != 'apple') {
$("<?php echo '#li_'.$unique ?>").hide();
};
});
});


I also tried..

$("<?php echo '#submit_'.$unique ?>").click(function(){
if ($("<?php echo '#select_'.$unique ?>").val() != 'apple') {
$("<?php echo '#li_'.$unique ?>").hide();
};
});

Answer

Working Fiddle.

You don't have to use the php code to generate the js code you could create a global event for all the li's :

$("[id^='submit_'").click(function(e){
  e.preventDefault();

  var unique = $(this).attr('id').split('_')[1];
  var default_value = $('#select_'+unique+' option:first').val();
  var current_value = $('#select_'+unique).val();

  if(current_value!=default_value)
      $('#id_'+unique).hide();
});

Hope this helps.

$("[id^='submit_'").click(function(e){
  e.preventDefault();

  var unique = $(this).attr('id').split('_')[1];
  var default_value = $('#select_'+unique+' option:first').val();
  var current_value = $('#select_'+unique).val();

  if(current_value!=default_value)
    $('#id_'+unique).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li id="id_1">
    <form id="form_1">
      <select id="select_1">
        <option value='apple' selected>Default1</option>
        <option value='pear'>Different1</option>
      </select>
      <input type="submit" id="submit_1"/>
    </form>
  </li>
  <li id="id_2">
    <form id="form_2">
      <select id="select_2">
        <option value='apple' selected>Default2</option>
        <option value='pear'>Different2</option>
      </select>
      <input type="submit" id="submit_2"/>
    </form>
  </li>
</ul>