Radio button check and uncheck onclick and send data - javascript

I'm trying to send data onclick via ajax with a radio button. If the radio button is clicked and checked, value of 1 is set in the database. If the radio button is already checked, but clicked to uncheck it, the value of 0 is sent to the database. The code I'm using sends the value onclick and checks the radio button but does not uncheck and hence does not send the value to the database. Please help.
<input type="radio" name="home['. $row["id"].']" id="'. $row["id"].'">
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var checked = $(this).prop('checked');
if (checked != 'checked') {
$(this).prop('checked', true);
var id = $(this).attr('id');
$.ajax({
url:"updateaddress.php",
method:"POST",
data:{home:"1",id:id,},
});
} else if (checked == 'checked') {
$(this).prop('checked', false);
var id = $(this).attr('id');
$.ajax({
url:"updateaddress.php",
method:"POST",
data:{home:"0",id:id,},
});
}
});
});
</script>

A checkbox and
$('input[type="checkbox"]').on("click", function(){
$.post("updateaddress.php",{home:this.checked,id:this.id});
});
is all you need
If you MUST use a radio, have a look at this
How to Check/Uncheck single radio button
$('input[type="radio"]').on("click", function(){
$.post("updateaddress.php",{home:this.checked,id:this.id});
this.checked=!this.checked;
});

Radio buttons are used when there is multiple options and user should check only one option.so,user can't uncheck a radio button when already checked.you explicitly make a onclick listener and change the radio button status.but it's not advisable.you can use checkbox for this purpose with onchange event.
$(checkEle).on("change",function(){
var status = $(this).prop("checked");
sendStatus(status);
}

<input type="radio" name="home['. $row["id"].']" id="'. $row["id"].'">
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var data = {home:"0",id:$(this).attr("id")};
if ($(this).is(":checked")) {
data = {home:"1",id:$(this).attr("id")};
}
$.ajax({
url:"updateaddress.php",
method:"POST",
data:data,
});
});
});
</script>
You can use this script.Just check if radio button is checked or not and send your values accordingly.

Related

Cannot uncheck checkbox

I am trying to uncheck a checkbox once my form is submitted
on the html side I have the following
<form class="form contact-form" id="contact_form">
<input type="checkbox" id="store_pickup" name="pickup" value="pickup" onclick="storeDetails()">
<label for="store_pickup">Store Pickup</label>
....
And then I have an existing JS file for the form which work for all other input types but Checkbox
$(document).ready(function(){
$("#submit_btn").click(function(){
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if (user_name == "") {
$('input[name=name]').css('border-color', '#e41919');
proceed = false;
}
if (user_email == "") {
$('input[name=email]').css('border-color', '#e41919');
proceed = false;
}
if (user_message == "") {
$('textarea[name=message]').css('border-color', '#e41919');
proceed = false;
}
//everything looks good! proceed...
if (proceed) {
//data to be sent to server
post_data = {
'userName': user_name,
'userEmail': user_email,
'userMessage': user_message
};
//Ajax post data to server
$.post('contact_business.php', post_data, function(response){
//load json data from server and output message
if (response.type == 'error') {
output = '<div class="error">' + response.text + '</div>';
}
else {
output = '<div class="success">' + response.text + '</div>';
//reset values in all input fields
$('#contact_form input').val('');
$('#contact_form textarea').val('');
// $('#store_pickup').attr('checked', false);
// $("#store_pickup").prop('checked', false);
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
return false;
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function(){
$("#contact_form input, #contact_form textarea").css('border-color', '');
// $("#store_pickup").attr('checked', false);
// $("#store_pickup").prop('checked', false);
$("#result").slideUp();
});
});
I've tried the two following statment commented out in the code but these do not work, can anyone assist me. Thank you!
You can toggle the checked attr of a HTML input of type="checkbox" with
$( elem ).prop('checked', false);
$( elem ).prop('checked', true);
You can check the current state of the checked property of the checkbox with
$( elem ).prop('checked')
You can also use Chrome Inspect tool to view/test the current properties of a DOM element by selecting the element and then viewing the 'properties' tab.
https://developers.google.com/web/tools/chrome-devtools/inspect-styles/edit-dom
Note: In my version of Chrome I have to deselect and then re-select the DOM element to see the properties refresh after modifying a property value with the above JS.
It's the presence of absence of a checked attribute that controls whether the checkbox is checked. Setting the value of the attribute has no effect.
So you need
$("#store_pickup").removeAttr('checked');

Validate checkbox using JavaScript.

I would like some help with checkbox validation.
If you look in below picture, when user click the image, the checkbox becomes selected.
What I would want is if all checkbox are selected alert an simple message.
This is a code to select checkbox by clicking on an image.
$( document ).ready(function() {
$("#roll-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>").click (function(){
var $$ = $(this)
if( !$$.is('.checked')){
$$.addClass('checked');
$('#imgCheck-<?php echo $row['id_vnr']; ?><?php echo $cut_counter; ?>').prop('checked', true);
}
});
});
So I can select check box by clicking on an image. How I can alert message if all check box are selected. Soon user click last picture, the picture will disappear, the red tick box will appear and user should see alert message.
Thank you in advance.
You can achieve this by getting the number of elements with the class 'checked'. If the number is 6, then you can show the alert.
Try this way:
var checkboxes = $('[type="checkbox"]');
checkboxes.on('change', function() {
var checked = $('[type="checkbox"]:checked');
console.log('all:', checkboxes.length, ' / ', 'checked:', checked.length);
if (checkboxes.length === checked.length) {
console.log('ALL CHECKED!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox">1
<input type="checkbox">2
<input type="checkbox">3
You can use the following javascript code:
$(function(){
$('input[type="checkbox"]').click(function() {
totalCheckboxCount = $('input[type="checkbox"]').length;
selectedBoxesCount = $('input[type="checkbox"]:checked').length;
if(totalCheckboxCount == selectedBoxesCount) {
alert("All checkboxes selected!");
}
});
});

localStorage : store checkboxes automatically checked

I have something like this in php:
if(isset($_POST['submit']){
$check = in_array($row['service_object_id'], $values) ? 'checked' : '';
}
echo '<input type="checkbox" class="faChkRnd" id="'.$row['service_object_id'].'" name="list[]" value="'.$row['service_object_id'].'" '.$check.'>';
Each time I press a submit button, it will check the checkboxes with values inside $check.
It's working good but I want to store the checkboxes checked in localStorage automatically after pressing the button.
I already use this script to store them after click, but it won't work automatically :
<script type = "text/javascript">
$('.faChkRnd').on('click', function() {
var fav, favs = [];
$('.faChkRnd').each(function() { // run through each of the checkboxes
fav = {id: $(this).attr('id'), value: $(this).prop('checked')};
favs.push(fav);
});
localStorage.setItem("favorites", JSON.stringify(favs));
});
$(document).ready(function() {
var favorites = JSON.parse(localStorage.getItem('favorites'));
if (!favorites.length) {return};
console.debug(favorites);
for (var i=0; i<favorites.length; i++) {
console.debug(favorites[i].value == 'on');
$('#' + favorites[i].id ).prop('checked', favorites[i].value);
}
});
</script>
Any ideas ? Thank you !
you shound check type of favorites[i].value. string or boolean !?
string :
if(favorites[i].value == "true") {
$('#' + favorites[i].id ).prop('checked',true);
}
boolean :
$('#' + favorites[i].id ).prop('checked',favorites[i].value);
example :
string : https://jsfiddle.net/utm4za2p/1/
boolean : https://jsfiddle.net/utm4za2p/3/
You can use submit method.
You have a form with the submit button and you have to change it to just a regular button.
And you should put
$('.yourForm').submit()
to the end of click handler where you save the values to the localStorage.
Because when you press the submit button it may triggered before your click handler.
You need save values first and then submit form.

how to add valaue of checkbox to url when checkbox clicked in javascript

<input class="messageCheckbox" type="checkbox" name="options[]" value="<?php echo $catrecord[0] ; ?>"/>
This is the check box and when some one select it i want to go to another url with checkbox valaue in url, not as post.
this is the place i wanna append checkbox valaue
case 'Addnew':
window.location = '<?php echo JURI::base()."index.php?option=com_flatorb&view=entity"?>';
break;
document.[name of form].[name of checkbox].checked
or with jQuery:
$('#[id of checkbox]').is(':checked');
You can bind change event handler with checkbox and use window.location to open page.
$('#checkboxId').change(function(){
if(this.checked)
window.location = 'index.php?option=com_flatorb&view=entity&chkValue=' + this.value;
});
You can do something like below,
Method 1
$('.messageCheckbox').change(function(){
if(this.checked)
window.location = 'index.php?option=com_flatorb&view=entity&value=' + $(this).val('');
});
Method 2
$('.messageCheckbox').change(function(){
if($('#edit-checkbox-id').is(':checked'))
window.location = 'index.php?option=com_flatorb&view=entity&value=' + $(this).val('');
})

Force AutoCompleteExtender dropdown to redisplay via Javascript

I have an AjaxControlToolkit.AutoCompleteExtender control attached to a textbox, and three radio buttons. When the user selects a radio button, the service method used to retrieve the values listed in the AutoCompleteExtender is changed, as follows:
$("#radioButtonList input").click(function() {
var selectedValue = $(this).val();
if (selectedValue == 0) {
$find('autoCompleteExtender').set_serviceMethod('AutoCompleteExtenderMethod1');
}
else if (selectedValue == 1) {
$find('autoCompleteExtender').set_serviceMethod('AutoCompleteExtenderMethod2');
}
else if (selectedValue == 2) {
$find('autoCompleteExtender').set_serviceMethod('AutoCompleteExtenderMethod3');
}
$('#textbox').focus();
}
I want to ensure that, if the user selects a radio button when text is already present in the textbox, the list of autocomplete values based on the new service method is displayed (just as it would be if the user clicked the radio button and then typed into the textbox).
I have tried various event-firing mechanisms, such as this:
var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 77;
$('#textbox').trigger(press);
...each of these...
$('#textbox').keydown();
$('#textbox').keypress();
$('#textbox').keyup();
and even:
$('#textbox').get(0).value += 'm';
but nothing seems force the correct events to fire in order to make the autocomplete list re-display with the results of the new service method. How can I make this happen using Javascript?
EDIT: I should note: the jQuery events are firing correctly in each of the above cases, they're just not causing the autocomplete list to reappear when they do. I figure I haven't yet struck the right combination of events that the autocompleteextender is expecting to force the list to appear.
Make sure that you bind your events in the $(document).ready() function. The following works correctly
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript">
</script>
<script>
$(document).ready(function(){
$("#radioButtonList input").change(function() {
var selectedValue = $(this).val();
if (selectedValue == 0) {
$find('autoCompleteExtender').set_serviceMethod('AutoCompleteExtenderMethod1');
}
else if (selectedValue == 1) {
$find('autoCompleteExtender').set_serviceMethod('AutoCompleteExtenderMethod2');
}
else if (selectedValue == 2) {
$find('autoCompleteExtender').set_serviceMethod('AutoCompleteExtenderMethod3');
}
//force click on text box
$('#textbox').click()
$('#textbox').focus();
});
//handle click event
$("#textbox").click(function(){
alert("textbox clicked")
//handle your refresh action for the textbox here
})
})
</script>
</head>
<body>
<input id="textbox" type="text" value="test">
<div id="radioButtonList">
<input type="radio" value="0">
<input type="radio" value="1">
<input type="radio" value="2">
</div>
</body>
</html>

Categories

Resources