简体   繁体   中英

I have a html page that loaded in div tag in another page using ajax call I want to trigger javascript functions on loaded page?

The main problem is the loaded html page contain loop of cards each card has checkbox I need trigger javascript function that check if checkbox selected then change text value in card to from select to selected, But the function I wrote to trigger this checkboxes not work? My checkbox tag from the appended html page:

<div class="body-action-button u-flex-center">
      <div><input type="checkbox" style="float: left;" name="companies[]" value="<?php echo $company->id; ?>" id="cbtest<?php echo $company->id; ?>" />
        Request an offer</div>
</div>

javascript function I used to trigger checkbox :

$('.body-action-button').click(function(){
        alert('selected');//This alert for testing
    });

Try this ( fiddle ): JS

$('input:checkbox[name=example]').each(function() {
  if (this.checked) {
    alert("selected");
  }
  // else {}
});

HTML

<input type="checkbox" name="example" /> label one
<input type="checkbox" name="example" checked/> label two

You can try to give a class to your checkboxes like

<input type="checkbox" class="cbxTest" style="float: left;" name="companies[]" value="<?php echo $company->id; ?>" id="cbtest<?php echo $company->id; ?>" />

and add your event to JQuery like that:

$(document).ready(function () {
    $(".cbxTest").click(function () {
        if (this.checked) {
            alert("Selected");
        }
    });    
});

Also if you want to not trigger it on click but only when checked you can also use .check instead of .click like that

$(document).ready(function () {
    $(".cbxTest").change(function () {
        if (this.checked) {
            alert("Selected");
        }
    });    
});

Both works well. It's just about the scenerio...

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