How to clear content of div using ICheck.js? - javascript

I want to clear the content of div after the checkboxes is unchecked. Also when the checkboxes is checked, the content should be visible.
I have tried it, but it won't clear the content after I uncheck the checkbox. It just add more content when its checked..
Here's my ajax code.
$('.myCheck').on('ifChecked', function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '/Home/getCategoryItems',
type: "GET",
cache: false,
data: {
name: $(this).attr("name")
},
success: function (data) {
$("#displayCarsSection").append(data);
}
});
} else {
$("#displayCarsSection").html('');
}
});

Since you want to clear check box specific data when it is unchecked, you can store it in an object. So, whenever a check box is checked or unchecked, you can clear the div and use that object to generate new data to append to div.
var checkBoxData = {};
$('.myCheck').on('ifChecked', function (event) {
var checkBoxIndex = $(this).index();
// This callback is triggered when checkbox is checked
$.ajax({
url: '/Home/getCategoryItems',
type: "GET",
cache: false,
data: {
name: $(this).attr("name")
},
success: function (data) {
checkBoxData[checkBoxIndex] = data;
updateCarsSection();
}
});
});
$('.myCheck').on('ifUnchecked', function (event) {
// This callback is triggered when checkbox is unchecked
checkBoxData[$(this).index()] = "";
updateCarsSection();
}
function updateCarsSection()
{
// Clear out the div
$("#displayCarsSection").empty();
var updatedData = "";
$.each(checkBoxData, function (key, value) {
updatedData += value;
});
// Append data based on currently selected checkboxes
$("#displayCarsSection").append(updatedData);
}

Why not use a change listener? As far as I know, 'click' should also work.
See https://jsfiddle.net/kkryao5g/1/
JavaScript
$('.myCheck').on('change', function (event) {
if ($(this).is(":checked")) {
$("#displayCarsSection").append($(this).attr('id'));
} else {
$("#displayCarsSection").html('');
}
});
HTML
<input type="checkbox" class="myCheck" id="myCheck1"> <label for="myCheck1">Option 1</label>
<input type="checkbox" class="myCheck" id="myCheck2"> <label for="myCheck2">Option 2</label>
<input type="checkbox" class="myCheck" id="myCheck3"> <label for="myCheck3">Option 3</label>
<br><br>
<span id="displayCarsSection"></span>

You have only a little mistake, you should use ifChanged callback instead of ifChecked.
$('.myCheck').on('ifChanged', function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '/Home/getCategoryItems',
type: "GET",
cache: false,
data: {
name: $(this).attr("name")
},
success: function (data) {
$("#displayCarsSection").append(data);
}
});
} else {
$("#displayCarsSection").html('');
}
});
So now, this will listen in every check/uncheck
Source: http://icheck.fronteed.com/

Related

How to use AJAX request to select radio button value and text inputs upon callback?

The form data fills properly on all input text fields. But for the radio buttons nothing happens except the value for the element gets changed, but no visual. I know its because based on the Class name, it changes the value. But how do i differentiate between field inputs vs radio inputs? thanks!
$(function() {
$(".task-listing").click(function() {
$.ajax({
type: 'POST',
url: 'http://localhost:8090/HELPERSITE/src/php/listing-info-get.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
console.log(response);
Object.keys(response[0]).map(function(k) {
var el = $('.' + k);
if (el.prop('type') == 'radio') {
el.filter(function(i, button) {
return button.value == response[0][k];
}).prop('checked', true);
} else {
$('.' + k).val(response[0][k]);
}
})
}
});
});
});
You need to set the checked property of the appropriate button if the type is radio.
$(function() {
$(".task-listing").click(function() {
$.ajax({
type: 'POST',
url: 'http://localhost:8090/HELPERSITE/src/php/listing-info-get.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
console.log(response);
Object.keys(response[0]).map(function(k) {
var el = $('.' + k);
if (el.prop('type') == 'radio') {
el.filter(function(i, button) {
return button.value == response[0][k];
}).prop('checked', true);
} else {
$('.' + k).val(response[0][k]);
}
if (response.negotiate == 'approve') {});
}
})
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="task-title-reg" name="task-title-reg" value="">
<textarea class="task-description-reg" name="task-description-reg" rows="4" cols="50" value=""></textarea>
<label for="local-reg">Local</label>
<input type="radio" name="task-location-reg" value="Local">
<label for="remote-reg">Remote</label>
<input type="radio" class="task-location-reg" name="task-location-reg" value="Remote">
<label for="approve-reg">Approve</label>
<input type="radio" class="task-negotiations-reg" name="negotiate" value="Approve">
<label for="deny-reg">Deny</label>
<input type="radio" class="task-negotiations-reg" name="negotiate" value="Deny">

How to render different url based on checkbox in Ajax?

I want to change the view of one page depending on which checkbox is checked.
Also when one is checked another becomes unchecked.
<input class="searchType" type="checkbox"></input>
<input class="searchType2" type="checkbox"></input>
I tried something like this but I don't know how to add another solution(if another checkbox is checked)
$('.searchType').click(function() {
alert($(this).attr('id')); //-->this will alert id of checked checkbox.
if(this.checked){
$.ajax({
type: "GET",
url: 'projects/index',
data: $(this).attr('id'),
success: function(data) {
alert('it worked');
alert(data);
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});
$('.searchType2').click(function() {
alert($(this).attr('id')); //-->this will alert id of checked checkbox.
if(this.checked){
$.ajax({
type: "GET",
url: 'projects/categories',
data: $(this).attr('id'),
success: function(data) {
alert('it worked');
alert(data);
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});
When I try code like this, in the server console I get for first checkbox:
Rendering projects/index.html.erb
Completed 200 OK in 217ms (Views: 197.8ms | ActiveRecord: 7.0ms)
And if other is checked
Rendering projects/categories.html.erb
Completed 200 OK in 217ms (Views: 197.8ms | ActiveRecord: 7.0ms)
It seems like it works but in reality, it does not change any route, all remains the same
Cheers
Since your route isn't working, you need to update the url, not the parameters.
So go the end result should be projects/index/searchType and not projects/index?searchType
The below snippet is an example that should cover all your questions.
It will uncheck any checkboxes that is not the checkbox doing the action. Though I would recommend using select or radio in this instance.
var searchType = document.getElementById("searchType"); //Get the checkbox element
var searchType2 = document.getElementById("searchType2");
searchType.addEventListener("change", search); //set the onchange event for each checkbox
searchType2.addEventListener("change", search);
function search() {
var checkbox = this;
var checkboxes = document.querySelectorAll("input[type=\"checkbox\"]");
for (var i = 0; i < checkboxes.length; i++) {
var chk = checkboxes[i];
if (chk !== checkbox) {
chk.checked = false;
}
}
if (checkbox.checked) {
$.ajax({
type: "GET",
url: 'projects/index/' + checkbox.id,
success: function (data) {
alert('it worked');
console.log(data);
$('#container').html(data);
},
error: function () {
console.log('it broke');
},
complete: function () {
console.log('it completed');
}
});
return;
}
console.log("no checkbox selected");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="searchType" class="searchType" type="checkbox"></input>
<input id="searchType2" class="searchType2" type="checkbox"></input>
Your input has no id attributes, please add the attributes
HTML
<input id="1" value="1" type="checkbox" class="searchType">
<input id="2" value="2" type="checkbox" class="searchType">
Javacript
$('.searchType').click(function() {
var input = $(this);
var val = input.val();
if(input.is(':checked')){
$.ajax({
type: "GET",
url: 'projects/index',
data: {id : val},
success: function(data) {
alert('it worked');
alert(data);
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});

Reset the data after unchecking the checkbox

I have some results in div's ,each result has one checkbox associated with it, when a user click on single checkbox user, Current checked box's value is passed to another page using an ajax call and data is fetched and displayed in a hidden div box.
Now problem is, when user uncheck the checkbox it should remove the data associated with the checkbox.
My code is :
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
Ajax call
<script type="text/javascript">
$(document).ready(function()
{
$(".compare").change(function() {
if(this.checked) {
var check = $(this).val();
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').append(data);
}
});
}
});
});
Use something like this to empty the contents of the DIV
$('#compare_box').empty()
better way is to keep the reference map, something like this
$(document).ready(function() {
var boxes = {};
$(".compare").change(function() {
var check = $(this).val();
var data = $(this).closest('.box').clone();
if (this.checked) {
boxes[check] = data;
$('#comparebox').append(boxes[check]);
} else if (!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
});
});
EDIT - should be working (not tested)
var check = $(this).val();
if (this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType: 'JSON',
data: {
value: check
},
success: function(data) {
boxes[check] = $(data);
$('#compare_box').append(boxes[check]);
}
});
} else if(!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
DEMO

Having issues on if-else statement on the text changed event

I have a little bit issue here on my html text changed event in regards with my if-else statement. Here's the scenario, I have the html layout below which has a dropdown list of all locations. Now, if type in your location on the input text box which has id of "#searchloc" it will query as you typed in and rebind the record list on the "#dropdownlist" div element. So my problem is, I want to rebind the "#dropdownlist" div element back to its default which shows all locations once I clear back or empty the "#searchloc" input textbox but the "#dropdownlist" div element remained clear or empty. Below I tried to use if-else statement to do this but I notice that under the else{...} statement it won't fire the function or even the alert method. How do I handle this type of issue in jquery?
HTML Layout:
<input type="text" id="searchloc" class="searchloc" onchange = "QueryLocation();" onkeydown="this.onchange();" onkeyup="this.onchange();" onkeypress = "this.onchange();" oninput = "this.onchange();" placeholder="Search Location" />
<div id="dropdownlist" data-bind="foreach: PopulateAllLocation" >
<div id="alllocationdiv" > <label id="listlocation" class="listlocation" data-bind="text: CityTown"></label></div>
</div>
jQuery:
// Change the dropdownlist result as text input change
function QueryLocation() {
if ($("#searchloc").val() != null) {
var dataObject = {
CityTown: $("#searchloc").val()
};
$.ajax({
url: '/OnlineStore/SearchLocation',
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: dataObject,
dataType: 'json',
success: function (data) {
self.PopulateAllLocation(data);
},
error: function () {
console.log('err')
}
});
}
else {
// Under this else statement won't fire any of this function...???
DisplayLocations();
alert("Textbox is empty...");
}
}
When you check for a value of an empty textbox in Javascript its not null its "" i.e empty string instead. So in your if condition the value is never equal to null, that is the reason the else part is never executed.
function QueryLocation() {
if ($("#searchloc").val() != "") {
var dataObject = {
CityTown: $("#searchloc").val()
};
$.ajax({
url: '/OnlineStore/SearchLocation',
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: dataObject,
dataType: 'json',
success: function (data) {
self.PopulateAllLocation(data);
},
error: function () {
console.log('err')
}
});
}
else {
DisplayLocations();
alert("Textbox is empty...");
}
}

How to show php passed results to ajax without refreshing

I want to do is when a user type an email to the inputbox ajax will pass the value automatically to php.
My problem is the result only show if I try to refresh the page
html:
<input type="text" id="email" name="email" />
script:
$(document).ready(function(){
var countTimerEmailName = setInterval(
function ()
{
emailName();
}, 500);
var data = {};
data.email = $('#email').val();
function emailName(){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: data,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
});
You can try with:
Because you dont need declare function in ready() and you need yo get the email value after any change. Now you only get the value when the page is ready.
function emailName( email ){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: 'email=,+email,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
$(document).ready(function(){
$('#email').change(function(e) {
emailName( this.val());
});
});
You're handling it wrong. jQuery has particular events to do these things.
Take this for example:
$(document).ready(function(){
$(document).on('keyup', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
It will look what is in the below input field as the user types. (which is what I presume you're trying to do?)
<input type="text" id="email" name="email" />
Example
You could simply remove that console.log() and replace it with your ajax request. (The above example will run as the user types.)
Alternatively you could use change() like this:
$(document).ready(function(){
$(document).on('change', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
Which will run after the value of the text box has changed. (When the user clicks out of the text box or moves somewhere else on the page.)
Example

Categories