开发者

Javascript/Jquery checkbox conditional hyperlink

开发者 https://www.devze.com 2023-01-26 13:29 出处:网络
I have a hyperlink/image button that uses javascript to submit开发者_如何学编程 a form, <p>

I have a hyperlink/image button that uses javascript to submit开发者_如何学编程 a form,

<p>
  <a href="#" onclick="checkOutFrm.submit();">
    <img src="images/btn-checkout-basket.gif" width="169" height="28" alt="Checkout" border="0" />
  </a>
</p>

and would like to add a checkbox that would disable the hyperlink until it is checked. How would I go about doing this?

Any help greatly appreciated, S.


You should not, in general:

  1. Mix your JavaScript into your HTML markup (you should attach your logic handlers programmatically),
  2. (ab)use anchor elements for JavaScript only (you should use a button, or put the onclick handler on the img directly), nor
  3. place a form's submission handler on the click of a single element (you should instead handle the onsubmit event of the form).

I don't know the specifics of your situation, but I would do this in your HTML file:

<!-- Put a valid doctype here -->
<html><head>
  <script type="text/javascript" src="submit.js"></script>
</head><body>
  <form id="myform" ...>
    <label>
      <input type="checkbox" name="accept" id="accept-box" />
      I accept
    </label>
    <button type="submit" id="submitter" disabled="disabled">
      <img src="..." />
    </button>
  </form>
</body></html>

...and this in your submit.js file:

window.onload = function(){
  var accept = document.getElementById('accept-box');
  var submit = document.getElementById('submitter');
  accept.onclick=function(){
    submit.disabled = !accept.checked;
  };
  document.getElementById('myform').onsubmit = function(){
    // Prevent form submission by any means unless
    // the accept button is checked.
    return accept.checked;
  };
};

(Well, actually, I personally would use jQuery for handling the JS side of things :)

$(function(){
  $('#accept-box').click(function(){
    $('#submitter').attr('disabled',!this.checked);
  });
  $('#myform').submit(function(){
    return $('#accept-box').attr('checked');
  });
});

You can use CSS to style away the button surrounding the image, if you like:

#submitter { border:0; padding:0 } 


Before submitting data, you can check the value of the checkbox first.

<a href="javascript: if(getElementById('CheckBoxID').checked) { checkOutFrm.submit(); } else { return false; }">

If you use jQuery you'd rather do it this way:

$(function(){
    $("a").click(function(e){
        e.preventDefault();
        $("#CheckBoxID").val() && $("form").submit();
    });
});


You can use Jquery Validator http://bassistance.de/jquery-plugins/jquery-plugin-validation/ to force it.

0

精彩评论

暂无评论...
验证码 换一张
取 消