Disable submit if checkbox value has not changed from initial page-render - javascript

I have a script that does not allow submit until the form value is changed from the initial page-render.
Everything works, except for the radio buttons. When I try to check or uncheck them, they have no effect on the button.
Anyone see what is wrong? (I want to do a check to see if one or more of the checkboxes has changed from the initial page-render)
$(document).ready(function () {
var button = $('#submit-data');
$('input, select, checkbox').each(function () {
$(this).data('val', $(this).val());
});
$('input, select, checkbox').bind('keyup change blur', function () {
var changed = false;
$('input, select, checkbox').each(function () {
if ($(this).val() != $(this).data('val')) {
changed = true;
}
});
$('#submit-data').prop('disabled', !changed);
});
});
Edit:
Checkbox html:
<input checked="checked" id="contactemail" name="contactemail" type="checkbox" />
<input id="contactsms" name="contactsms" type="checkbox" />
<input checked="checked" id="contactphone" name="contactphone" type="checkbox" />
Edit 2:
New code from answer from Marikkani Chelladurai. It is almost working, but it only works if the checkbox is not checked initially, and then checked by the user. Link to JSFiddle
$(document).ready(function() {
var button = $('#submit-data');
$('input, select').each(function () {
$(this).data('val', $(this).val());
});
$('input[type=radio], input[type=checkbox]').each(function (e) {
$(this).data('val', $(this).attr('checked'));
}); //For radio buttons
$('input, select').bind('keyup change blur', function (e) {
var changed = false;
if (e.target.type == "radio" || e.target.type == "checkbox" ) {
if($(this).data('val') != $(this).attr('checked')){
changed = true;
}
} else {
if ($(this).val() != $(this).data('val')) {
changed = true;
}
}
$('#submit-data').prop('disabled', !changed);
});
});
Link to JSFiddle

You can handle radio buttons and checkboxes by a different way as follows
$('input, select').not('[type=checkbox]').each(function () {
$(this).data('val', $(this).val());
});
$('input[type=radio], input[type=checkbox]').each(function (e) {
$(this).data('val', $(this).is(':checked'));
}); //For radio buttons
$('input, select').bind('keyup change', function (e) {
var changed = false;
if (e.target.type == "radio" || e.target.type == "checkbox" ) {
console.log($(this).is(':checked'));
console.log($(this).data('val'));
if($(this).data('val') != $(this).is(':checked')){
changed = true;
}
} else {
if ($(this).val() != $(this).data('val')) {
changed = true;
}
}

As the comments say, radio buttons use the checked property. Pass in event to your each and check the target.type:
$('input, select, checkbox').each(function (e) {
if (e.target.type == "radio") {
//check radio
} else {
if ($(this).val() != $(this).data('val')) {
changed = true;
}
}
});

Related

How to get the switch toggle state(true/false) in javascript

I have a switch toggle which has following code, following one of the StackOverflow questions I did similarly
Here's How to add the text "ON" and "OFF" to toggle button
<label class="switch">
<input type="checkbox" id="togBtn" value="false" name="disableYXLogo">
<div class="slider round"></div>
</label>
and in css i am disabling input checkbox
.switch input {display:none;}
then how would I get the true/false value of that switch toggle button.
I tried this but it doesn't work for me
$("#togBtn").on('change', function() {
if ($(this).is(':checked')) {
$(this).attr('value', 'true');
}
else {
$(this).attr('value', 'false');
}});
How would I get the check/uncheck or true/false value in js for my toggle switch button
The jquery if condition will give you that:
var switchStatus = false;
$("#togBtn").on('change', function() {
if ($(this).is(':checked')) {
switchStatus = $(this).is(':checked');
alert(switchStatus);// To verify
}
else {
switchStatus = $(this).is(':checked');
alert(switchStatus);// To verify
}
});
You can achieve this easily by JavaScript:
var isChecked = this.checked;
console.log(isChecked);
or if your input has an id='switchValue'
var isChecked=document.getElementById("switchValue").checked;
console.log(isChecked);
This will return true if a switch is on and false if a switch is off.
$("#togBtn").on('change', function() {
if ($(this).is(':checked')) {
$(this).attr('value', 'true');
alert($(this).val());
}
else {
$(this).attr('value', 'false');
alert($(this).val());
}
});
if want to access table row
$('body').on('change', '#statusSwitch', function () {
if ($(this).is(':checked')) {
****Your logic*****
}
else {
***Your logic***
}
});
$("#togBtn").on('change', function() {
if ($(this).attr('checked')) {
$(this).val('true');
}
else {
$(this).val('false');
}});
OR
$("#togBtn").on('change', function() {
togBtn= $(this);
togBtn.val(togBtn.prop('checked'));
}

jquery disable submit button unless all radio button group checked

Trying to disable a form submit button unless a selection has been made from a number of radio button groups. Have got this far, cant see why not working, button stays disabled:
<script>
$(function () {
$('#button').attr('disabled', true);
var disable = true;
$('input:radio').click(function () {
$('input:radio').each(function () {
if ($(this).is(':checked'))
disable = false;
else
disable = true;
});
});
$('#button').prop('disabled', disable == true ? true : false);
});
</script>
You should probably change the property inside the handler, and the right handler for a radio button would be onchange
$(function () {
var button = $('#button').prop('disabled', true);
var radios = $('input[type="radio"]');
var arr = $.map(radios, function(el) {
return el.name;
});
var groups = $.grep(arr, function(v, k){
return $.inArray(v ,arr) === k;
}).length;
radios.on('change', function () {
button.prop('disabled', radios.filter(':checked').length < groups);
});
});
FIDDLE

Making submit button active when there is text in textfields - jquery

i have a script which check when two textfields are not empty it does automatic submission. it picks the variables from the localstorage and places them in the textfields.
if (localEmail != null && localPwd != null) {
$('#form1').submit();
}
and i also i have a script which disables the submit button when all textfields are not filled.
$(document).ready(function (){
var $input = $('#form1 input:text'),
$register = $('#button_id');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.button('disable') : $register.button('enable');
});
});
now my problem is when the page loads for the second and subsequent times and there are variables from the localstorage in the textfields, the submit button still remains disabled and the automatic submission fails. Now i want the button to remain active when there are variable in it so the automatic submission can be done
In document ready do an additional check for input values and disable the button
$(document).ready(function () {
var $input = $('#form1 input:text'),
$register = $('#button_id');
$input.each(function () {
if (!$(this).val()) {
$register.attr('disabled', true);
return false;
}
});
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
});
$(document).ready(function () {
var $input = $('#form1 input:text'),
$register = $('#button_id');
$input.each(function () {
if (!$(this).val()) {
$register.attr('disabled', true);
return false;
}
});
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="form1">
<input type="text" />
<input type="text" />
<button id="button_id">button</button>
</form>
The reason why you are not achieving the desired behavior is because you are only updating the button's disabled property when a change event is fired from the input element(s), which are not fired by default upon page load.
The solution is to therefore move the function involving updating the button's status into a separate one, which we will call upon runtime (e.g. DOM ready) and then again when the change event is fired on element(s) of interest:
var updateButton = function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.button('disable') : $register.button('enable');
};
// Update button status on DOM ready
updateButton();
// Update button status on keyup
$input.keyup(updateButton);
On a side note, please use .prop() when dealing with binary attributes:
$register.prop('disabled', true);
this should work
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
under document ready function.
$(document).ready(function (){
var $input = $('#form1 input:text');
$register = $('#button_id');
$register.prop('disabled', true);
//$register.attr('disabled', true);
$('#button_id').on('click',function(){alert('hi');});
function checkInputs(){
$input.each(function(e) {
if (!$(this).val().length < 1) {
trigger = true;
} else
{trigger = false;}
});
trigger ? $register.prop('disabled',false) : $register.prop('disabled',true);
}
checkInputs();
$('#form1 input:text').on('keyup',function(){checkInputs();});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<input/>
<input />
<button type="button" id="button_id" >Submit</button>
</form>

jQuery Arguments Not Working

Having trouble with 2 things. Both of these arguments are ONLY working for the first box area generated on page load. But any subsequent ones created after aren't affected by these options. What am I doing wrong, and how can I fix it?
//CHECK IF TYPE/PAGE(S) IS SELECTED OR NOT
$(".dropdown").change(function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty").children('.placeholder').remove();
});
//CHECKS TO MAKE SURE ONLY ONE CHECKBOX IS SELECTED
var $onlyOne = $('.onlyOne');
$onlyOne.click(function () {
$onlyOne.filter(':checked').not(this).removeAttr('checked');
});
The entire code for my JS is:
$(function () {
var i = 1;
//ADD ROW
$('body').on('click', '.addPTbutton', function () {
var box = '<table class="manage-pt" id="' + i + '"><tr class="pt-entry"><td class="pt-toggle-group"><input class="pt-button togPTbutton" id="0" type="button" value="▾"><input class="pt-button addPTbutton" id="0" type="button" value="+"><input class="pt-button delPTbutton" id="' + i + '" type="button" value="-"></td><td class="pt-values"><div><input class="vendor grayout" placeholder="*Vendor Name" type="text"><select class="move-me-right-10 dropdown"><option value="0" class="placeholder" selected="selected">*Select Type</option><option value="analytics">Analytics</option><option value="chat">Chat</option><option value="remarketing">Remarketing</option><option value="other">HTML/CSS/JS</option></select><i class="icon-sort"></i><i class="icon-lock"></i></div><div><textarea class="ptCode" name="ptCode" placeholder="*Pixel Tag Code"></textarea></div><div class="page-select"><select class="dropdown"><option value="0" class="placeholder" selected="selected">*Select Page(s)</option><option value="AllPages">All Pages</option><option value="HomePage">HomePage</option><option value="VehicleDetailsPage">VehicleDetailsPage</option><option value="VehicleSearchResults">VehicleSearchResults</option><option value="ContactUsForm">ContactUsForm </option></select></div><div class="area-checkboxes"><p class="wheretosave">*Where?</p><input name="head" type="checkbox"><label for="head">Head</label><input name="body" type="checkbox"><label for="body">Body</label></div><hr/></td></tr></table>';
i++;
$("#p_scents").append(box);
return false;
});
//DELETE ROW
$('body').on('click', '.delPTbutton', function () {
var boxnum = $(".manage-pt").length;
if (boxnum <= '1') {
alert('Cannot Delete Last Remaining Row');
} else {
$(this).parents().eq(3).remove();
}
return false;
});
//TOGGLE BUTTON
$('body').on('click', '.togPTbutton', function () {
var hiddenarea = $(this).parent().next().children().next();
if ($(hiddenarea).is(':hidden')) {
//PT-VALUES OPENED
$(this).val('▾');
$(this).parent().next().children(0).children(0).attr('readonly', false);
//$(this).parent().next().children(0).children(1).prop('disabled', false);
} else {
//PT-VALUES HIDDEN
$(this).val('▸');
$(this).parent().next().children(0).children(0).attr('readonly', true);
//$(this).parent().next().children(0).children(1).prop('disabled', 'disabled');
}
//TOGGLE VISIBILITY OF HIDDEN AREA
hiddenarea.toggle();
});
//CHECK IF TYPE/PAGE(S) IS SELECTED OR NOT
$(".dropdown").change(function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty").children('.placeholder').remove();
});
$(".dropdown").change();
//CHECKS FOR MORE THAN ONE 1 MANAGE-PT BEFORE ENABLES SORTABLE
$('body').on('mouseenter', '.icon-sort', function () {
if ($(".manage-pt").size() > 1) {
$('#p_scents').sortable({
disabled: false,
placeHolder: '.placeHolderHighlight',
handle: '.icon-sort',
});
} else $('#p_scents').sortable({
disabled: true,
});
});
//CHECKS TO MAKE SURE ONLY ONE CHECKBOX IS SELECTED
var $onlyOne = $('.onlyOne');
$onlyOne.click(function () {
$onlyOne.filter(':checked').not(this).removeAttr('checked');
});
//LOCK BUTTON ON/OFF LOCKS FORM
$('body').on('click', '.icon-lock', function () {
$(this).toggleClass('locked');
var lockedarea = $(this).parents(0).eq(2);
$(lockedarea).find('input[type=text],input[type=checkbox],textarea,select').prop('disabled', function (_, val) {
return !val;
});
});
});
I assume you're using AJAX. You should be handling event delegation differently for dynamically generated DOM elements.
Ideally, you shouldn't be using body or document. Try using the nearest parent selector which is present all the time(non AJAX).
//CHECK IF TYPE/PAGE(S) IS SELECTED OR NOT
$("body").on("change", ".dropdown", function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty").children('.placeholder').remove();
});
//CHECKS TO MAKE SURE ONLY ONE CHECKBOX IS SELECTED
$("body").on("click",'.onlyOne', function () {
$onlyOne.filter(':checked').not(this).removeAttr('checked');
});

Looking for a hand on my jQuery and JS script

What I have is in my fiddle here http://jsfiddle.net/mPuj9/4/
What I tried to do is to disable the button until all of textboxes are filled and the checkbox is checked. My current code is not good, it let you submit in some cases and I don't know how to work it with the checkbox.
CODE
$(document).ready(function() {
$('.textfield').blur(function() {
if ($.trim(this.value) == "") {
$('#btnUpdate').attr("disabled", true);
}
else {
$('#btnUpdate').removeAttr("disabled");
}
});
});
$(document).ready(function() {
$('#termid').change(function() {
var val = $(this).val();
$('#reservationdetails').empty().addClass('loading').load('../kratisis/forms/' + val + '.php', function() {
$('#reservationdetails').removeClass('loading')
});
});
});
Here you go
http://jsfiddle.net/mPuj9/8/
$(document).ready(function () {
$('form').delegate('input:text, input:checkbox', 'blur keyup change', function () {
if(($('form input:text').filter(function(){ return $.trim(this.value) == ''; }).length > 0)
|| ($('form input:checked').length == 0)){
$('#btnUpdate').attr("disabled", true);
}
else {
$('#btnUpdate').removeAttr("disabled");
}
});
});
Here's another way you could do this, which also works if someone presses enter in a text box, or if the browser autofilled an input:
$(function() {
$("form button").attr("disabled", true); //disable buttons at first
var inputs = 0; //keep count of the inputs
$("form input, form select, form textarea").each(function() {
inputs++; //increment counter
$(this).keypress(function() {
if ($.trim($(this).val()) != "") { //if the value isnt empty
inputs--; //decrement counter
if (inputs == 0) { //if theyre all filled in
$("form button").attr("disabled", false);
}
}
}).trigger("keypress"); //in case it was autofilled by the browser
});
$("form").submit(function(e) { //prevent the form being submitted by pressing enter
if (inputs != 0) { //if they arent all filled in
alert("Some fields aren't filled in. Please fix them and try again."); //tell the user
e.preventDefault(); //cancel sending the form
return false;
}
});
});
I think the problem is that you're not using .each() for the text fields. You're checking the one that was recently changed to see if it's value is "", but you're not checking each one.

Categories