Reset the data after unchecking the checkbox - javascript

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

Related

AJAX not sending current value of selected option

php code
<?php
if(isset($_POST['data'])) {
$file_handle = fopen('my_file.json', 'w');
fwrite($file_handle, json_encode($_POST['data']));
fclose($file_handle);
}
?>
html
<h1 id="title" class="text-lg-center text-md-center text-sm-left mb-4">test
title</h1>
<p class="lead text-lg-center text-md-center text-sm-left mb-4">test
content</p>
<button id="test" type="button" class="btn btn-lg btn-block btn-outline-
success">Publish List</button>
<div class="form-group">
<label for="exampleFormControlSelect1">Example select</label>
<select class="form-control" id="selectfont">
</select>
</div>
javascript
$(function () {
var font = 0;
var font_names = ["Montez","Lobster","Josefin Sans"];
$.each(font_names , function (index , value) {
$('<option />' , {
'value' : index,
'text' : value
})
.css({'font-family' : font_names[index]})
.appendTo("#selectfont");
});
$("#selectfont").change(function () {
var font = $(this).val();
$("p").css('font-family' , font_names[font]);
});
var htmldata = {
'content_font_type': font_names[font],
'content_font_size': parseFloat($("title").css('font-size'))
};
$("#test").click( function(){
$.ajax({
method: "POST",
url: "test.php",
data: {data: htmldata},
success: function(data) {
alert(data);
}
});
});
});
so what i want to ask is why in my_file.json the content_font_type and content_font_size not changing, but when i use alert() function in $("#selectfont").change it show correctly. Also, success always return empty when i use console.log and alert()
You have two problems:
When #selectfont changes, you're setting a local variable font, not the global variable, because you re-declare it with var font. Get rid of the var keyword.
You're setting htmldata when the page first loads. You need to set it when the user clicks on the button, so you get the updated values.
You don't really need the font variable at all. You can get the value of #selectfont when you're setting htmldata.
$("#test").click( function(){
var htmldata = {
'content_font_type': font_names[$("#selectfont").val()],
'content_font_size': parseFloat($("title").css('font-size'))
};
$.ajax({
method: "POST",
url: "test.php",
data: {data: htmldata},
success: function(data) {
alert(data);
}
});
});

If contains help text display on view?

Currently I have a div class by default displaying none, however I want the value from help text if it contains the help text. I think something like if value from dropdown contains help text display.show
Below is my div
<div class="alert alert-info col-md-12" id="ProfHelpAlert" role="alert" style="display:none">
<i class="fa fa-info-circle" aria-hidden="true"></i>
<strong class="notification" id="ProfHelp"></strong>
</div>
This is my JavaScript
$('#profession').on('change', function (e) { //Gets the ID of profession drop down list
var selectedVal = $(this).val(); //Variable selectedVal this . value
$.ajax({ //Ajax declared
type: 'GET', //Its a get
url: "#Url.Action("GetenquiryTypes", "UnauthEnquiry")", //It goes to the enquiry controller method GetenquiryTypes
dataType: 'json', //Datatypes JSON
data: { SelectedProfession: selectedVal }, //data is SelectedProfession: selectedVal
success: function (json) { //Jquery Parse Json data from server on ajax success
$('#ProfHelp').html(json.helptext);
var targetDropdown = $('#enquirytype') //Var targetDropDropdown goes to dropdown ID enquiry type
targetDropdown.empty(); //target empty dropdown
$("<option />", {
val: "",
text: "Please select enquiry type" //Select enquiry type
}).appendTo(targetDropdown); //add to the target dd
if (json.enquiryTypes.length > 0) { //if JASON data from server greater then 0
for (var EnquiryType in json.enquiryTypes) { //go through each EnquiryType in JSON
$("<option />", {
val: json.enquiryTypes[EnquiryType].EnquiryId, //mapping
text: json.enquiryTypes[EnquiryType].Enquiryname //mapping
}).appendTo(targetDropdown); //add to drop down
};
}
}
});
});
Are you saying you want to show your help message when the ajax method succeeds? If so, is this what you are looking for?
success: function(json) {
//... add to end of method
if(json.helptext) {
$('#ProfHelpAlert').show();
}
}
Do you need a comparison to the value of the select?
success: function(json) {
//... add to end of method
if(json.helptext == selectedVal) {
$('#ProfHelpAlert').show();
}
}

How to clear content of div using ICheck.js?

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/

AJAX filled Select2 not clickable

I'm using Select2 for a project. The second select box gets filled depending on the selected item in the first box, as shown in the link below. However, I can't click the first item in the second select box for some reason. The only way for me to select the first item if I want to, is to first select a different user, and then back to the first. How can I solve this?
Video:
My code:
This is the first select box, getting filled by regular PHP (Laravel). Everything works fine here.
<div class="form-group">
<label for="select"> Partner: </label>
<select id="select" name="select" class="searchselect searchselectstyle">
#foreach($partners as $i => $partner)
<option {{$i == 0 ? 'selected' : ''}} value="{{$partner->id}}">{{$partner->name}}</option>
#endforeach
</select>
</div>
Here Is the second select box, with the error.
<div class="form-group" >
<label for="select2"> Hoofdgebruiker: </label>
<select id="select2" style="min-width: 200px;" name="select2" class="searchselect searchselectstyle">
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
var url = '/json/getusers';
var $post = {};
$post.id = $("select").val();
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: $post,
cache: false
}).done(function(data){
$('#select2')
.find('option')
.remove()
.end();
$.each(data, function(i, value) {
console.log(data);
$('#select2').append($('<option>').text(value.text).attr('value', value.id));
});
}
);
});
-
public function getusers(){
if(!isset($_POST['term'])){
$users = User::where('partner_id', $_POST['id'])->get();
}else{
$wildcard = '%'.$_POST['term'].'%';
$users = User::where('partner_id', $_POST['id'])->where('email', 'LIKE', $wildcard)->get();
}
$array = array();
foreach($users as $i => $user){
$array[$i] = array("id" => $user->id, "text" => $user->email);
}
return response()->json($array);
}
Check the case sensitivity of the key "id" in json data. Probably you return "ID" insteat of "id".
{"results":[{"id":"3","text":"Exampe 3"},{"id":"4","text":"Example 4"},{"id":"16","text":"Example 16"}]}
not like that
{"results":[{"ID":"3","text":"Exampe 3"},{"ID":"4","text":"Example 4"},{"ID":"16","text":"Example 16"}]}
I found a solution, which is the following:
<script type="text/javascript">
$(document).ready(function() {
$(".searchselect").select2();
search();
$("#select").change(function(){
search();
});
});
function search(){
var $post = {};
$post.id = $("#select").val();
$("#select2").select2({
ajax: {
dataType: "json",
type: "POST",
data: function (params) {
var query = {
term: params.term,
id: $post.id
};
return query;
},
url: '/json/getusers',
cache: false,
processResults: function (data) {
return {
results: data
};
}
}
});
}
</script>
Now I'm using the regular AJAX functionality built in Select2, it is all working as expected now!

How to send multiple variables through ajax?

The code below sends the id of item to more.php to load more content. It works fine. Now to add some more features I need to send one more id to more.php through the same code.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.display').append(html);
}
});
});
});
</script>
Suppose second id is var catid = '<?php echo $cat ?>'; how to send this catid through the same ajax code. data : {id : id, catid : catid} is something I should do but can't get how to deal in current situation when my data carries data:'id='+ID,.
your should look like. specify your data as an object:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.show_more', function () {
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type: 'POST',
url: 'more.php',
data: { id:ID, userid: userid },
success: function (html) {
$('#show_more_main' + ID).remove();
$('.display').append(html);
}
});
});
});
To retrieve multiple input's I suggest combining them in a Form:
first embed your inputs in an form with a submit button, you should also not use the same name twice because it won't work now, create unique names
<form action="GET" id="myForm">
<input id="string" type="text" name="string" />
<input id="string2" type="text" name="string" />
<input type="submit" value="Go" />
</form>
and write code to submit the ajax way
$('#myForm').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var $form = $(this);
$.ajax({
type: "GET",
url: "retrieve.php",
data: $form.serialize(), //make it JSON
success: function() {
console.log("it worked");
}
});
});

Categories