How to combine toggle on off with http.get - javascript

I try make toggle with bootstrap toggle and give som function http.get if toggle click on or off. But i have some trouble if on clicked it work but if off clicked it didn't work. My code like this
<input id="toggle-two" type="checkbox" data-toggle="toggle" data-width="100">
<script>
$(function() {
$('#toggle-two').bootstrapToggle({
on: 'Lock',
off: 'Unlock'
}).on('change', function() {
$.ajax({
url: 'http://localhost/web.php?tN=rlock&f12=123456789',
data: { checked: $(this).prop('checked') },
success: function() {
console.log('Lock');
}
});
}).off('change', function() {
$.ajax({
url: 'http://localhost/web.php?tN=runlock&f12=123456789',
data: { checked: $(this).prop('checked') },
success: function() {
console.log('Unlock');
}
});
});
});
</script>
i don't know how to fix it, please helpme to solve my problem

You can try something like this
<input id="toggle-two" type="checkbox" data-toggle="toggle" data-width="100">
<script>
$(function() {
$('#toggle-two').bootstrapToggle({
on: 'Lock',
off: 'Unlock'
}).on('change', function() {
var Checked_or_not = this.checked, // check if checked or unchecked
tN = Checked_or_not ? 'rlock' : 'runlock'; // if checked return 'rlock' if unchecked return 'runlock' for tN in url
$.ajax({
url: 'http://localhost/web.php?tN='+ tN +'&f12=123456789', // add tN in url
data: { checked: Checked_or_not },
success: function() {
console.log('Lock');
}
});
});
});
</script>

Related

AJAX/jQuery generated inputs not recognized by other jQuery scripts

I have what I assume is a relatively simple issue. For testing purposes I have made it so simple so as to locate the issue.
I have a jQuery script that works alongside AJAX to return some results next to checkboxes, here it is below:
$.ajax({
type:'GET',
url: '/customers/details/emails',
dataType:'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i,val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" id="emailCheckboxSelect">'),
$('<td>').text(val)).appendTo('#customerEmails');
});
}
}
});
As you can see near the end, for each result a table row is appended, with a checkbox with an id of "emailCheckboxSelect".
Now to my problem, these are obviously dynamically created elements so I believe this is the issue with this script (a simple dummy just to locate the issue). Here is that script that should work:
$(function(){
$('#emailCheckboxSelect').click(function(){
alert('clicked');
});
});
This doesn't work with the dynamically created elements. However, I did add <input type="checkbox" id="emailCheckboxSelect">Checkbox directly to my page, and this does set off the alert.
So what am I doing wrong and what do I need to do so that jQuery can recognize dynamically created elements?
Try to bind the click event after the $.each(data, function() {}) inside the sucess: function() {}
You are using multiple elements with same id in the DOM : Element IDs should be unique within the entire document.
use classes instead
your code will look like:
$.ajax({
type: 'GET',
url: '/customers/details/emails',
dataType: 'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function() {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {
timeOut: 5000
});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i, val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" class="emailCheckboxSelect" />'),
$('<td>').text(val)).appendTo('#customerEmails');
});
$('.emailCheckboxSelect').click(function(e) {
alert('clicked');
});
}
}
});
Try changing your click event to something like
$('td').on('click', '.emailCheckboxSelect', function () {
alert('clicked');
});
This would work on dynamically created elements. Also, use class instead of id for dynamically created elements.

Displaying delete icon when checkbox is selected - JS

I am trying to do this, when a user checks at least one box, the icon must show if not, it hides.
With my code, when i select the #mastercheckbox, the icon does show but when i select the other checkbox displaying on each row, it doesn't show.
Why is this happening?
HTML:
<table id="users-table" class="table table-hover table-condensed" style="width:100%">
<thead>
<tr>
<th><input type="checkbox" id="master"></th>
<th>Category</th>
<th>Description</th>
<th>Number of Items</th>
<th>Action</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$(document).ready(function() {
oTable = $('#users-table').DataTable({
"processing": true,
"serverSide": true,
"bProcessing":false,
"bSort":false,
"ajax": "{{ route('datatable.getcategories') }}",
"columns": [
{data: 'checkbox', name: 'checkbox', orderable: false, searchable: false},
{data: 'name', name: 'name'},
{data: 'action', name: 'action', orderable: false, searchable: false}
],
});
});
</script>
Controller:
$stduents= Student::all();
return Datatables::of($student)->addColumn('checkbox', function ($std) {
return '<input type="checkbox" class="sub_chk" data-id="'.$std->id.'">';
})->make(true);
Where i select my checkbox:
<script type="text/javascript">
$(document).ready(function () {
$("i[type='icon']").css('display','none'); //set style explicitly
$('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
} else {
$(".sub_chk").prop('checked',false);
}
});
$('.delete_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
var check = confirm("Are you sure you want to delete this row?");
if(check == true){
var join_selected_values = allVals.join(",");
$.ajax({
url: $(this).data('url'),
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
location.reload();
alert(data['success']);
}
else if (data['error'])
{
alert(data['error']);
}
else
{
//alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
$.each(allVals, function( index, value )
{
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.trigger('confirm');
}
});
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
location.reload();
alert(data['success']);
}
else if (data['error']) {
alert(data['error']);
}
else
{
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
});
</script>
Display icon when at least one checkbox is selected:
<script>
$("input[type='checkbox']").click(function() {
var atLeastOneChecked = false;
$("input[type='checkbox']").each(function(index) {
if ($(this).prop('checked'))
atLeastOneChecked = true;
});
if (atLeastOneChecked) {
$("i[type='icon']").show(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','inline-block'); //or set style explicitly
} else {
$("i[type='icon']").hide(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','none'); //set style explicitly
}
});
</script>
Since your checkboxes are added after the page load $("input[type='checkbox']").click(...) will not add the event handler to them. i.e.
//will handle clicked events on checkbox existing when this js runs
$('input[type="checkbox"]').click(function() {
alert('clicked')
});
//will handle clicked events on dynamically added checkboxes
$(document).on('click', 'input[type="checkbox"]', function() {
alert('clicked2');
});
//add new checkbox to page
$('button').click(function() { $('#master').after($('<input type="checkbox" >')) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="master">
<button type='button'>Add Checkbox</button>
What you want to do instead is $(document).on('click', 'input[type="checkbox"]', function() { ... }
A simple example works for me - whatever is going wrong for you, you'll have to either provide more code or narrow in on the problem with some debugging of your own.
Hope this helps: master and grouped checkboxes all react to click
HTML:
<div id="icon">SEE ME?</div>
<div id="info">Information</div>
<div><input type="checkbox" id="master"></div>
<div><input type="checkbox" name="subset01[]" value="00"></div>
<div><input type="checkbox" name="subset01[]" value="01"></div>
<div><input type="checkbox" name="subset01[]" value="02"></div>
<div><input type="checkbox" name="subset01[]" value="03"></div>
<div><input type="checkbox" name="subset01[]" value="04"></div>
<div><input type="checkbox" name="subset01[]" value="05"></div>
<div><input type="checkbox" name="subset01[]" value="06"></div>
<div><input type="checkbox" name="subset01[]" value="07"></div>
<div><input type="checkbox" name="subset01[]" value="08"></div>
<div><input type="checkbox" name="subset01[]" value="09"></div>
CSS:
#icon{ display: none; }
JS:
$( function(){
$('#info').text("please click a checkbox");
$( "input[type='checkbox']" ).click( function(){
$('#info').html( "you clicked # "+ new Date().getTime() +" currently "+ $(':checked').length +" checked" );
if( $(':checked').length ){
$("#icon").show();
}else{
$("#icon").hide();
}
} );
} );

Send multiple checkbox data with ajax

I have a form where I have countries list in checkbox format to be inserted into database. Say for example:
<input type="checkbox" name="country[]" value="Afghanistan" checked>Afghanistan<br>
<input type="checkbox" name="country[]" value="Albania" checked>Albania<br>
<input type="checkbox" name="country[]" value="Algeria" checked>Algeria<br>
<input type="checkbox" name="country[]" value="American Samoa" checked>American Samoa<br>
<input type="checkbox" name="country[]" value="Andorra" checked>Andorra<br>
<input type="checkbox" name="country[]" value="Angola" checked>Angola<br>
<input type="checkbox" name="country[]" value="Anguilla" checked>Anguilla<br>
I want to insert this into database using ajax. I could have easily done this through normal same page PHP post. But when sending data with ajax to other page for processing I am confused on how to send. Once it sends all the selected checkbox values perfectly then all the rest is onto me.
My AJAX script
$("#submit").click(function() {
var dataString = {
clicks: $("#clicks option:selected").data("value"),
country: $("input[name=country").data("value") // tried using this and input[name=country[]] but they did not work.
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to purchase this advertisement?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType : "json",
url: "add-ptc-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#loading-rent").hide();
$("#submit").show();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
}
}
});
return false;
});
});
I have put a check on the processing page where if the country value is empty return error like:
if($country == ''){
echo "No countries selected. Please select at least one country.";
}
No matter if I select one or all countries still I get this error response back. What should I do to send these checkbox data with ajax?
Try
var countries = {};
$('input[name^="country"]').each(function(){
countries[$(this).attr('value')] = $(this).is(":checked");
});
then post it to ajax data: countries or change the code to send only checked elements
Your PHP will receive an array so you can check
if(is_array($_POST['countries'])){
foreach($_POST['countries'] AS $country_name => $is_checked){
//do something...
}
}
You will want to switch your .data() to .val() on your input capture. Also change the name of the inputs to input[name=country\\[\\]]:checked.
# Use "e" as the event
$("#submit").click(function(e) {
# Use this function to stop the form
e.preventDefault();
# You could make a quick function to save all the countries
# You can actually feed other selectors into this as well, so
# it can do all your value retrievals, not just for countries
function getCountries(checkboxes)
{
var getVals = [];
$.each($(checkboxes),function(k,v) {
getVals.push($(v).val());
});
return getVals;
}
var dataString = {
clicks: $("#clicks option:selected").val(),
# Run the function to gather
# Note the name (escaped [] with :checked)
country: getCountries("input[name=country\\[\\]]:checked")
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to purchase this advertisement?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType: "json",
url: "add-ptc-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#loading-rent").hide();
$("#submit").show();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
}
}
});
});

Form doesn't submit form data populated via AJAX

I'm having the following problem with my code below: when 'productSearchResult' is populated via AJAX, the contents are not included when the form is submitted using the 'Add' button.
UPDATE 1:
Strangely it is working, but only the first time productSearchQuery is populated. Any subsequent populations of productSearchQuery run into the problem above.
HTML:
<form name="productSearch">
<input name="productSearchQuery" type="textbox">
</form>
<form name="productAdd">
<div id="productSearchResult"></div>
</form>
<a>Add</a>
<div id="addResult"></div>
HTML loaded via AJAX into productSearchResult:
<input type="radio" name="productId" value="3944">
<input type="radio" name="productId" value="3946">
<input type="radio" name="productId" value="3999">
JS:
<script type="text/javascript">
function postData(type, url, data, targetDiv) {
$.ajax({
type: type,
url: url,
data: data,
success: function(response) {
$(targetDiv).html(response);
},
error: function() {
alert('Error! Plese try again.');
}
});
return false;
};
$(document).ready(function() {
$('input[name=productSearchQuery]').keyup(function() {
// submit the form
postData('POST', 'search.php', $('form[name=productSearch]').serialize(), '#productSearchResult');
});
$('a').click(function() {
postData('POST', 'add.php', $('form[name=productAdd]').serialize(), '#addResult');
});
});
</script>
UPDATE 2:
OK, first off I want to apologise for not including this code in my original post, I honestly didn't suspect it could be the cause. I've fixed my code after rolling back the JS which is returned with the radio buttons. I can't understand why the new JS causes the problem above, whereas the old JS does not.
Here's the old JS that works fine:
$('tr.product input[type=radio]').hide();
$('tr.product').mouseover(function() {
$(this).addClass('blueHover');
}).mouseout(function() {
$(this).removeClass('blueHover');
});
$('tr.product').click(function(event) {
$('tr.product').removeClass('blueChecked');
$(this).closest('tr').addClass('blueChecked');
if (event.target.type !== 'radio') {
$(':radio', this).attr('checked', true);
}
});
Here's the new JS that causes the problems above:
$('tr.product input[type=radio]').hide();
$(document).on({
mouseenter: function () {
$('td', $(this).parent()).addClass('blueHover');
},
mouseleave: function () {
$('td', $(this).parent()).removeClass('blueHover');
},
click: function (event) {
$('tr.product').removeClass('blueChecked');
$(this).closest('tr').addClass('blueChecked');
if (event.target.type !== 'radio') {
$(':radio', $(this).parent().parent()).attr('checked', false);
$(':radio', $(this).parent()).attr('checked', true);
}
}
}, 'tr.product td');
Try this instead
<script type="text/javascript">
function postData(type, url, data, targetDiv) {
$.ajax({
type: type,
url: url,
contentType: 'application/json',
data: data,
success: function(response) {
$(targetDiv).html(response);
},
error: function() {
alert('Error! Plese try again.');
}
});
return false;
};
$(document).ready(function() {
$('input[name=productSearchQuery]').keyup(function() {
// submit the form
postData('POST', 'search.php', $('form[name=productSearch]').serialize(), '#productSearchResult');
});
$('a').click(function() {
postData('POST', 'add.php', $('form[name=productAdd]').serialize(), '#addResult');
});
});
</script>
You have to use jQuery on method.
$('body').on('click', 'a', function() {
postData('POST', 'add.php', $('form[name=productAdd]').serialize(), '#addResult');
});

Ajax call on checking a checkbox

I am having a two checkboxes.Now on click of one of the checkbox I want to make an ajax call to a jsp page.That jsp page is to show a table that contains datat being fetched from database.
Now,The problem is say i have two checkboxes like :
<div class="search-inputs">
<input class="searchName" type="text" placeholder="Search Here.."></input>
<input class="searchType1" type="checkbox" name="emailNotification"><label class="searchtype1label">Email Notification</label></input>
<input class="searchType2" type="checkbox" name="SharingNotification"><label class="searchtype2label">File Sharing Notification</label></input>
<input class="searchDateFrom" type="text" placeholder="Search From"></input>
<input class="searchDateTo" type="text" placeholder="Search To"></input>
<input class="Datesubmit" type="button" value="Search"></input>
<div id="container"></div>
How to do it ?Please help
My Script part :
$(document).ready(function () {
$('.search-select').on('change', function(){
$('.search-inputs').children().hide();
var classn =$(this).find(":selected").val();
//alert(classn);
if(classn=='searchName')
{
//alert("searchname");
$('.'+"searchName").show();
}
else if(classn=='searchType')
{
//alert("searchType");
$('.'+"searchType1").show();
$('.'+"searchtype1label").show();
$('.'+"searchType2").show();
$('.'+"searchtype2label").show();
}
else if(classn=='searchDate'){
//alert("searchType");
$('.'+"searchDateFrom").show();
$('.'+"searchDateTo").show();
$('.'+"Datesubmit").show();
}
});
$('#emailNotification').on('change',function() {
//var checked = $(this).is(':checked');
if(this.checked){
//alert("in");
$.ajax({
type: "POST",
url: "searchOnType.jsp",
data: {mydata: "emailNotification"},
success: function(data) {
alert('it worked');
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});
});
But how to show the table on the same page ?
you have to change your html slightly with this--
give same class name to both check boxes.
<input class="searchType" type="checkbox" name="emailNotification" id="emailNotification"><label class="searchtype1label">Email Notification</label></input>
<input class="searchType" type="checkbox" name="SharingNotification" id="SharingNotification"><label class="searchtype2label">File Sharing Notification</label></input>
Now slightly change in jquery part--
$('.searchType').click(function() {
alert($(this).attr('id')); //-->this will alert id of checked checkbox.
if(this.checked){
$.ajax({
type: "POST",
url: 'searchOnType.jsp',
data: $(this).attr('id'), //--> send id of checked checkbox on other page
success: function(data) {
alert('it worked');
alert(data);
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});
you have to use change event for this like below:
Html:
<input class="searchType1" type="checkbox" name="emailNotification"><label class="searchtype1label">Email Notification</label></input>
<input class="searchType2" type="checkbox" name="SharingNotification"><label class="searchtype2label">File Sharing Notification</label></input>
<div id="container">
</div>
JQuery:
$('#emailNotification').on('change',function() {
if(this.checked){
$.ajax({
type: "POST",
url: "searchOnType.jsp",
data: {mydata:"emailNotification"},
success: function(data) {
alert('it worked');
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});

Categories

Resources