user3089927
user3089927

Reputation: 3905

generate alert on button click based on input type hidden

I have html that has tile view and each tile has some info with button. I want to check the value of an input hidden field and if the value is not in array defined raise an alert.

html

  <div class="box" style="width:30%%">
  <div class="boxInner">

  <form id="form_myws" method="POST">
  <input type="hidden" name="state" value="%s">
   <div class="titleBox">
      <input type="submit" value="submit" name="ws_butt" id="submit" />
    </div>

  </form>
  </div>
  </div>

javascript

<script type="text/javascript">
$('#submit').click(function(){
    var state_list=["AVAILABLE","IMPAIRED","INOPERABLE",];
    var curr_state=$(this).find("input[type='hidden'][name='state']");
    console.log(curr_state.val());
    if (jQuery.inArray(curr_state.val(),state_list)<0){
            alert("submission is allowed only with AVAILABLE,IMPAIRED,INOPERABLE states.");
    }
});

It is not generating any alert. How to achieve that?

Upvotes: 0

Views: 590

Answers (3)

GuoX
GuoX

Reputation: 421

in your case:

 var curr_state=$(this).find("input[type='hidden'][name='state']");

$(this) get the button element you selected , you can't find any childen nodes via find() So you should select the hidden input correctly like:

 var curr_state=$($(this).parent()[0]).prev()[0];

or like this:

    var curr_state=$($(this).parent()[0]).siblings('[name="state"]')[0];

Upvotes: 0

Remere
Remere

Reputation: 61

var curr_state=$(this).find("input[type='hidden'][name='state']");

change it to

var curr_state=$(this).closest('form').find("input[type='hidden'][name='state']");

also add

return false;

inside if statement so it won't submit form.

Upvotes: 1

wahwahwah
wahwahwah

Reputation: 3177

If you want to subvert submit you need to do:

$('#submit').click(function(e){

    // this:
    e.preventDefault();

    // more code

    // .. or better
    return false;

});

You can contain these responses in if --> then constructs but you need to do one or the other to prevent a form from submitting. If you're not using a form, don't use submit!

You can also access the hidden input value like this:

$('#form_myws > input[name="state"]').val();

Working snippet:

var val = $('#form_myws > input[name="state"]').val();

$('body').append(val);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form id="form_myws">
  <input type="hidden" name="state" value="%s">
  <div class="titleBox">
    <input type="submit" value="submit" name="ws_butt" id="submit" />
  </div>

</form>

Upvotes: 0

Related Questions