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');
}
});
}
});
Related
Okay so I have multiple forms on the page, the difference is their id, also each one has a parent box, all of which also have a different id.
The html of one of the box:
<div class="center-block" id="box2">
<form action="/login" id="form2" method="post" novalidate="novalidate">
<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="2">
<input id="Name" name="Name" type="hidden">
<input type="submit" value="Submit">
</form>
</div>
I submit the forms with ajax, and what I want to do is find the id of the box that had its form submitted.
This is the script:
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function () {
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Here I would like to alert the id of the parent box.
//Something like this:
alert($(this).closest('div').attr('id'));
//Which returns undefined
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});
</script>
Any idea how I would do that?
$(this) won't work in success callback. $(this) is relative, the scope of $(this) will be of success callback. You need to assign a variable first & then use it in success callback
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function () {
var curr_form = $(this);
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Here I would like to alert the id of the parent box.
//Something like this:
curr_form.closest('div').attr('id')
//Which returns undefined
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});
</script>
Just use the JQuery parent() method:
alert($(this).parent().attr('id'));
Also, as others have pointed out, you have a different issue in that this isn't pointing to the form when you use it in the success callback. You should cache that value and then use the cache variable. You can read more about how this works in JavaScript in another post of mine.
$(document).ready(function() {
$('form').submit(function () {
// Cache the object that "this" is bound to because
// in the success function, the invocation context
// changes and "this" won't point to the same object
// it does now.
var theForm = this;
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Just use the JQuery parent() method with the cached object
$(theForm).parent().attr('id')
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});
I have a JSON file, js/links.json:
{ "allLinks": [
{
"Link": "http://bbc.com",
"Poster": "John"
},
{
"Link": "http://espn.com",
"Poster": "Jane"
}
...etc.
and the following HTML:
<input placeholder="http://" id="urlField" type="text">
<button type="button" id="search" name="button">Search</button>
<div id="result"></div>
The behaviour I would like is:
You enter a link into the input
When the button is clicked, get the links.json array and loop through it.
If the link exists, output into #result: "This exists, and was posted by [poster]"
If it does not exist, output into `#result"This link does not exist."
This is how I'm trying to do it now:
$(function(){
$.ajax({
type : 'GET',
url : 'js/links.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(jsonResult){
$("#search").click(function() {
var searchValue = document.getElementById('urlField').value;
// Go through the whole list and find the Link name
var linkExists = false;
$.each(jsonResult.allLinks, function(i, obj) {
if (obj.Link === searchValue ) {
linkExists = true;
alert("It exists");
return false;
}
else {
linkExists = false;
alert("It doesn't exist");
return false;
}
});
});
}
});
});
There's definitely something wrong here because, if I don't use the else, it appears to work. When I add it, it doesn't— it always defaults to "It doesn't exist."
Thanks in advance for the help.
Pull the contents of your else statement outside of the for loop, otherwise you alert failure every time you hit the first element and it doesn't produce a match.
$(function() {
$.ajax({
type: 'GET',
url: 'js/links.json',
async: false,
beforeSend: function() { /*loading*/ },
dataType: 'json',
success: function(jsonResult) {
$("#search").click(function() {
var searchValue = document.getElementById('urlField').value;
// Go through the whole list and find the Link name
var linkExists = false;
$.each(jsonResult.allLinks, function(i, obj) {
if (obj.Link === searchValue) {
linkExists = true;
alert("It exists");
return false;
}
});
if (!linkExists) {
alert("It doesn't exist");
return false;
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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/
When the user tries to check an unchecked checkbox (I do nothing if it's already checked), I prevent the checkbox from getting checked and validate it with an AJAX call. But I can't figure out how to "check" it again. I tried to use $(this).trigger('click'); but it doesn't work.
I also tried moving preventDefault to the fail condition. But that made the call not work, ever. I guess because the AJAX call changes the scope.
$(document).ready(function(){
$('input:checkbox').click(function(e) {
if( $(this).prop('checked') && $(this).val()=='on' )
{
e.preventDefault();
var name = $(this).attr('name');
var pivot_attendee_program = name.split(/\]\[|\[|\]/);
var data = {
'pivot' : pivot_attendee_program[0],
'attendee_id' : pivot_attendee_program[1],
'program_id' : pivot_attendee_program[2]
};
//console.log(data);
$.ajax({
type: "GET",
url: '{{ route('ageCheck') }}',
data: data,
success: function(result){
console.log('success');
if(result == 'pass'){
console.log('pass');
$(this).trigger('click');
}
else{ //result == 'fail'
console.log('fail');
}
},
error: function(result){
alert(JSON.stringify(result));
}
});
//validate Age
//ajax check age of attendee against program
//ajax check age of attendee against program_seg
}
});
});
use the context: option to pass this through to the success function, then set the checked property of the box:
$.ajax({
type: "GET",
url: '{{ route('ageCheck') }}',
data: data,
context: this,
success: function(result){
console.log('success');
if(result == 'pass'){
console.log('pass');
$(this).prop("checked", true);
}
else{ //result == 'fail'
console.log('fail');
}
},
error: function(result){
alert(JSON.stringify(result));
}
});
For some reason, my script isn't writing out the text after I remove the textbox element. Am I incorrectly using the .html or is something else wrong?
$('.time').click(function () {
var valueOnClick = $(this).html();
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove('.timebox');
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});
OK, thanks to the comments, I figured out I was referencing the wrong thing. The solution for me was to change the blur function as follows:
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
}
$(this).parent().html("8");
$(this).remove('.timebox');
});
$(this) in your success handler is refering to msg, not $('.timebox') (or whatever element that you want to append the html to)
$(this) = '.timebox' element but you have removed it already,
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88"); // This = msg
}
and
else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88"); // this = '.timebox' element but you have removed it already,
}
The value of this changes if you enter a function. So when u use this in the blur function handler, it actually points to '.timebox'
$('.time').click(function () {
var valueOnClick = $(this).html();
var $time=$(this);//If you want to access .time inside the function for blur
//Use $time instead of$(this)
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove(); //Since $(this) now refers to .timebox
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});