简体   繁体   中英

onsubmit check if checked and change source

this doesn't seem to work, and resets checked...would like to only update if checked

<iframe id="time" name="time" type="text/html" src="http://time.is/"></iframe>

<form id="url" onsubmit="" method="post">
<input type="text" name="target" id="target" value="http://time.is" size="40"></form>

<input type="checkbox" name="check1" />
$('.url').submit {
    if($('input[name="check1"]', this).is(':checked')) {
        document.getElementById(time).src = url;
    } else {
        alert('no');
    }
    return false;
});

http://jsfiddle.net/ZZe5X/57/

Because you put check box out side the form but in code you call if ($('input[name="check1"]', this).is(':checked')) { should move check box inside form and also remove onsubmit=""

<div class="c">
   <iframe id="time" name="time" type="text/html" src="http://time.is/" frameborder="0" allowtransparency="true"></iframe>
</div>
<form id="url" method="post" target="time">
   <div>
      <input type="text" name="target" id="target" value="http://time.is" size="40">
      <input type="checkbox" name="check1" />
   </div>
</form>

<script>
   $(function(){
       $('#url').submit (function(){
          if ($('input[name="check1"]', this).is(':checked')) {
            document.getElementById('time').src = url;
          } else {
            alert('no');
          }
          return false;
       });
   });
</script>

http://jsfiddle.net/ZZe5X/66/

There are multiple errors:

1.you need to add submit button inside html form (or have a way to trigger form submission with JavaScript), something like this:

<input type="submit"/>

2.the varible url is undefined, you may add the following line in the JavaScript

var url = $('#target').val();

3.

document.getElementById(time).src = url;

should be

document.getElementById('time').src = url;

4.change the first line of script from

$('.url').submit {

to

$('#url').submit(function() {

5.as Trinh Hoang Nhu said, check box should be inside form because you are using

if ($('input[name="check1"]', this)...

Here's the updated test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM