I am using CSS toggle button to show active or inactive. It uses a HTML checkbox and modifies its CSS to look like toggle slide bar. I have bound the onClick event on the checkbox so that when the checkbox is checked it sends id via an AJAX request to a URL that updates the status of the row with the given id to active and echoes active. The PHP echo returned by URL is now displayed below the toggle button.
Here, when checkbox is clicked first the checkbox is checked and the AJAX request is sent to the URL, what I want is when the checkbox is clicked the checkbox doesn't get checked or unchecked but the AJAX request is sent and when response arrives then only change status of checkbox to checked or unchecked as per the response. How can I achieve this? Can someone clarify with an example?
The ajax handler code is:
function toggleStatus(id)
{
$.ajax
({
url: "project/news/toggleStatus?id="+id,
type: 'get',
success: function(result)
{
$('#status_txt'+id).html(result);
$('#status_txt'+id).attr('class', 'status_'+result);
},
error: function()
{
$('#modalinfo div').html(' <div class="modal-content"><div class="modal-header"><h2>Could not complete the request.</h2></div></div>');
$('#modalinfo').modal('show');
}
});
}
The html is:
<td class="numeric"><label class="switch">
#if($data->status=="active")
<input class="switch-input" type="checkbox" onClick="javascript:toggleStatus({{$data->id}})" checked="checked"/>
#else
<input class="switch-input" type="checkbox" onClick="javascript:toggleStatus({{$data->id}})"/>
#endif
<span class="switch-label" data-on="On" data-off="Off"></span>
<span class="switch-handle"></span>
</label>
<span id="status_txt{{$data->id}}" class="status_{{$data->status}}">#if($data->status=="inactive")<p style="color:red;">{{ ucfirst($data->status) }}</p>#else{{ ucfirst($data->status) }}#endif</p></span>
</td>
use java script:
suppose checkbox id="ck"
<input type="checkbox" id="ck" onClick="if(ck==1)unChecked();else doChecked();">
ck=0; //init checkbox is unchecked
function doChecked(){
document.getElementById("ck").checked="checked";
document.getElementById("ck").checked=true;
ck=1;
}
function unChecked(){
document.getElementById("ck").checked="";
document.getElementById("ck").checked=false;
ck=0;
}
Firstly I would suggest removing the onclick attribute from your checkboxes HTML; they're outdated, ugly and bad for separation of concerns. You're using jQuery for your AJAX, so you may as well use it to hook up your events too.
Secondly, You can prevent the default behaviour of the checkbox to stop the check appearing when the element is clicked. You can then set the checked property manually in the success callback of the AJAX request, something like this:
<input type="checkbox" name="foo" id="foo" value="foo" />
$(function() {
$('#foo').change(function(e) {
e.preventDefault();
var checkbox = this;
var id = checkbox.id;
$.ajax({
url: "project/news/toggleStatus?id="+id,
type: 'get',
success: function(result) {
checkbox.checked = true;
$('#status_txt' + id).html(result).attr('class', 'status_' + result);
},
error: function() {
$('#modalinfo div').html('<div class="modal-content"><div class="modal-header"><h2>Could not complete the request.</h2></div></div>');
$('#modalinfo').modal('show');
}
});
});
});
It is worth nothing though is that this behaviour is non-standard. By that I mean that the user will click the checkbox and it will appear that nothing has happened until the request completes. This may confuse your user in to clicking the checkbox again, and causing repeated AJAX requests. I would suggest you add a loading indicator to the page when the checkbox is clicked so that it's obvious that work is being done based on the users' actions.
Also, I would strongly suggest you use DOM traversal to find the related #status_txtXXXX elements from the clicked checkbox instead of ugly concatenated ids - it's better semantically and means the JS is less coupled to the UI.
Related
I have three radio buttons and I want, by default, to have the "BOTH" location which has a value of 3 to be clicked on page load so that it will run my jQuery post function. The radio button is filled-in giving the appearance of being clicked, but the click is not happening to post my function. Once I change the radio button however, the code works fine.
This is my code:
$("input:radio[name='location'][value='3']").click();
$('input[name="location"]').change(function() {
var location = $('input[name="location"]:checked').val(); var category = getUrlVars()["category"];
$.post(
'db/functions/package_conf.php',
{category:category, location:location},
function(data) {
$('#package_info').html(data);
});
});
Would you try to register the event handle first before trigger the event? $("input:radio[name='location'][value='3']").click(); after the .change' event..
you may consider use the checked too, like $("input:radio[name='location'][value='3']").prop("checked", true).
but for my personally preference, any default state should be done before hand and not the in the script, for example initiate your radio DOM element to have checked property <input type="radio" value="3" checked />, and then onLoad script call the post directly (anyway POST is not designed for this purpose, just imagine POST as to save something, if you just want to get/query some data, GET would be more reasonable)
click was triggered before the change's event handler was regestered.
$('input[name="location"]').change(function() {
var location = $('input[name="location"]:checked').val(); var category = getUrlVars()["category"];
$.post(
'db/functions/package_conf.php',
{category:category, location:location},
function(data) {
$('#package_info').html(data);
});
});
$("input:radio[name='location'][value='3']").click();
$(window).on('load', (e) => { $("#test").focus() })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test" value="23" type="number" style="font-size:30px;width:150px;">
I do have a checkbox list and when you click on one of them it should be update the page via AJAX
$(document).on("click", ".selectlist input", update_results);
So my client asked me to make one of those "checked" by default.
basically you can do it with this code
$('input#my_id').prop('checked', true);
But the thing is the AJAX will be work just when you click on the item.
Is there anyway either change the AJAX to when input is checked not click or make the checkbox clicked onLoad?
Thanks
HTML:
<input type="checkbox"/>
JS:
$(document).ready(function() {
$('input').trigger('click');
});
JSFiddle: http://jsfiddle.net/9z8panbn/
i am using a table with different rows and an edit button on each row.
This edit button creates a form using ajax / json to fill the form details depending on the row clicked.
The problem then comes when creating the ajax for this form.
Im using the same method as always, but for some reason the ajax submission is not working on this form and its just going to the process PHP page.
Im just wondering if this is because the form is not on the page when the javascript code for the ajax call is loaded?
So an example:
1) The page is loaded and included on that page is:
<script type="text/javascript" src="admin/js/showUserDetailsForm.js"></script>
<script type="text/javascript" src="admin/js/saveUserDetails.js"></script>
2) I click edit, and the showUserDetailsForm.js creates the form. The form is this:
$('<div id="admin-edituser-popup">'+
'<div id="login-popup-title">Edit User:<button id="closeedituserform">Close</button></div>'+
'<div id="login-popup-centre">'+
'<form class="editUserDetails-form" action="admin/process/saveUserDetails.php" method="POST">'+
'Editing Details for User:'+response.username+' , User ID:'+response.userID+
'<input type="hidden" name="userid" value="'+response.userID+'">'+
'<input type="text" name="username" value="'+response.username+'">'+
'<input type="submit" value="Save User">'+
'</form>'+
'</div>'+
'</div>').appendTo('body');
3) I click the submit button, and its correctly returns the JSON i am looking for (updateSuccess).
4) The form is not processed via ajax, its simply going to where its action is.
The code for the ajax call on save details is:
// JavaScript - Save user details
$(document).ready(function(){
// When the form is submitted
$(".editUserDetails-form").submit(function(){
$.ajax({
type: "POST",
url: "admin/process/saveUserDetails.php",
data: $(".editUserDetails-form").serialize(),
dataType: "json",
success: function(response){
if (response.updateSuccess) {
alert('Saved');
}
}
});
return false;
});
});
I cannot see any reasons why that its not working (cant find any errors with class names etc) and there is not errors in the javascript.
The only thing i am unsure of is the fact that the form is created AFTER the code is loaded?
Thanks!
For newly created DOM element handlers, you should use JQuery's on().
For your issue, you should just replace $(".editUserDetails-form").submit(function(){ with $("body").on('submit', '.editUserDetails-form', function(){
Last but not least, #Brunis is right - you should add event.preventDefault() to your method (event parameter is automagically injected)
If you want to intervene the default behaviour you should either
1. use e.preventDefault() in your onsubmit event callbackFunction or
2. use a "script" button that doesn't submit, eg. button type=button will not submit, but then you'll have to adjust your onsubmit event to just be an onclick event for that button.
Also, there's no need to have method and action in your form element when you don't want that to happen.
Consider the following code (http://jsfiddle.net/FW36F/1/):
<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].checked;">toggle</button>
If you click the checkbox, you get an alert telling you if it's checked or not. Great. However, if you click the toggle button, the checkbox changes it's checked state but the onchange event is NOT fired.
Essentially, the onchange for a checkbox only fires if the user actually clicks the checkbox, not if the checkbox is changed via JavaScript. This is be true in IE, FF, and Chrome. It appears that this behavior is to specification also.
However, I really need some kind of event to fire if, for any reason, the checkbox's checked state changes. Is this possible?
Oh yeah, and jQuery is not allowed. And please no setTimeout/setInterval based solutions either...
Update: Also, I should make it clear that the code above is for illustration only. In the real code, we need to ensure the state of the checkbox is checked or unchecked -- not just toggle it. Perhaps this would be better code to illustrate that:
<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].checked=true;">check</button>
<button onclick="document.getElementsByTagName('input')[0].checked=false;">un check</button>
Moreover, there may be code in other areas we don't fully control, which might do a simple .checked=true/false -- we'd like to make sure we see that also.
The existing answers work just fine, even with your update. Just be smart about it and don't call click if you don't need to. Also, please don't use inline JS. That was OK 10 years ago.
<input type="checkbox" onchange="alert(this.checked)">
<button id='check'>check</button>
<button id='uncheck'>uncheck</button>
document.getElementById('check').onclick = function() {
if (!this.checked) {
this.click();
}
}
If you need to be modified when a script changes the value, in Firefox, you can use https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch
Example here http://jsfiddle.net/PPuZ8/
// In FF $ is a shortcut for document.getElementById
// It doesn't fire when set from the UI, you have to use a regular handler for that
$('cb').watch("checked", function(){
console.log('Checked state changed from script', arguments);
return true;
});
For IE you can use onpropertychange http://msdn.microsoft.com/en-us/library/ie/ms536956(v=vs.85).aspx (Thanks to jivings for the reminder)
Example: http://jsfiddle.net/PPuZ8/1/
document.getElementById('cb').onpropertychange = function() {
if (event.propertyName == 'checked') {
console.log('Checked state changed onproperty change');
}
};
For other browsers, you have to poll using setInterval/setTimeout
Have the toggle button actually click the checkbox:
<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].click()">
toggle
</button>
If you wanted any change to the checkbox to inform you of its new position, then I would create a global method for changing the value of the checkbox, and deal with it as a proxy:
<script>
function toggleCB( state ) {
var cb = document.getElementById("cb");
arguments.length ? cb.checked = state : cb.click() ;
return cb.checked;
}
</script>
<input id="cb" type="checkbox" />
<input type="button" onClick="alert( toggleCB(true) )" value="Check" />
<input type="button" onClick="alert( toggleCB(false) )" value="Uncheck" />
<input type="button" onClick="alert( toggleCB() )" value="Toggle" />
Now anytime you set or toggle the checkbox, you'll get the checked state back.
One last thing, I would avoid using the onClick attribute, and instead bind the click events up from within your JavaScript.
Use click()
<button onclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].click();">toggle</button>
oninput is the event you need to handle ...
https://developer.mozilla.org/en/DOM/DOM_event_reference/input
I have a few radio buttons which should call hider(something); when they change, meaning when they are checked or unchecked. This works, i.e. when checked they call the JS function, however, if they're unchecked due to selecting another radio button from that group, it does not call the js script again.
Do I need to use something else than onchange?
This is what the radio buttons look like at the moment:
<input name="ostype" type="radio" value="0" onchange="hider(solaris);">solaris
<input name="ostype" type="radio" value="1" onchange="hider(linux);">linux
My hider function is currently:
function hider(divid) {
if ($(divid).is('.hidden')) {
$(divid).removeClass('hidden');
} else {
$(divid).addClass('hidden');
}
}
Since this question is still not answered correctly yet ranks quite high for me in Google for "radio button onchange", here's a proper solution for anyone still looking.
If you're using jQuery, just use jQuery's attribute selector as noted by Flavius Stef.
OP, it's not entirely clear what your code does. Let's assume in your code you want to add the "hidden" class to whatever radio button is active.
$("your selector here").change(function() {
$('input[name="' + this.name + '"]').removeClass("hidden");
$(this).addClass("hidden");
});
Please note the difference between $(this) (the jQuery object) and this (the DOM object). Basically I'm removing the "hidden" class from every input that goes by the same name, and then I add the "hidden" class to the current input.
Of course I'm assuming here that you're not using duplicate names for different inputs on the page. Also note that this would only work for radio buttons, as the radio button "change" event only fires when activated, not when deactivated.
Listening for onchange on both checkboxes and radio buttons
In my case, I wanted to add a "checked" class to active radio buttons and checkboxes. Since the checkbox fires the "onchange" event both when checked and unchecked, I needed a bit of extra code.
$('input[type="radio"]').change(function() {
$('input[name="' + this.name + '"]').removeClass("checked");
$(this).addClass("checked");
});
$('input[type="checkbox"]').change(function() {
$(this).toggleClass("checked", ($(this).is(":checked")));
});
The latter function uses toggleClass to set the "checked" class if .is(":checked") is true.
Alternatively you might want to combine the two functions into something like:
$('input[type="radio"], input[type="checkbox"]').change(function() {
if(this.type == "radio")
$('input[name="' + this.name + '"]').removeClass("checked");
$(this).toggleClass("checked", ($(this).is(":checked")));
});
Either way, always be careful when listening for an onclick event as it will not fire when the input is activated through keyboard navigation.
Use onclick.
Also as the argument of your function call you'll need to either use a string with the id as a jQuery selector ('#solaris') - better yet use this:
<input name="ostype" type="radio" value="0" onclick="hider(this);">solaris
Bind change event to ALL radio buttons on document ready:
$(function(){
$('input[name=list_type]:radio').on("change", function(){
showHideBlock();
});
showHideBlock();
});
Show -- hide block depends on ONE radio button status:
function showHideBlock(){
if ($("#Option").is(':checked')){
$('#Block').show();
} else {
$('#Block').hide();
}
}
<input name="ostype" type="radio" value="0" onclick="hider('solaris');">solaris
<input name="ostype" type="radio" value="1" onclick="hider('linux');">linux
function hider(divid) {
$( 'div.div_class' ).hide();
$( '#' + divid ).show();
}
Make sure you add a class to call the divs and make sure you put quotes around solaris and linux in the function calls
Here's a version that you might draw inspiration from (tested on Chrome and FF):
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
</head>
<body>
<input type="radio" name="ostype" checked="checked" onclick="hider('linux')">linux
<input type="radio" name="ostype" onclick="hider('solaris');">solaris
<div id="content">
<div id="linux">linux</div>
<div id="solaris" style="display:none;">solaris</div>
</div>
<script>
function hider(divname) {
$('#content div').each(function(){
$(this).hide();
});
$('#'+divname).show();
}
</script>
</body>
</html>
If I understand you correctly you can just use an onClick on every button and hide the others while showing the one your clicking on.
Like this:
function showInfo(info)
{
var info = document.getElementById("1");
info.style.display = "block";
var info = document.getElementById("2");
info.style.display = "none";
}
So the first one is showing and the second one is hiding.
Then just add one for every div that should be hidden.
You can also do this with jQuery.
function showAndHide(val1, val2)
{
$(val1).hide();
$(val2).show();
}
And don't forget to have style="display:none" in every div.
did you declare the vars solaris and linux?
otherwise your browser should show you an Error