Jquery - Identify if radio button value has not changed - javascript

Is it possible to identify if the value of radio button has not changed?
Currently I am trying to change the confirmation message of submit button on button changed, and do not want any message if the value has not changed. I have something like this now:
$('input[type="radio"]').change(function() {
var selected = $('input:checked[type="radio"]').val();
if(selected == 'true') {
$("#submit_button").data("confirm", "foo");
} else if(selected == 'false') {
$('#fee').hide();
$("#submit_button").data("confirm", "bar");
}
This will change confirm message to foo if button selected is true, and bar if button selected is false. However, what if I want to return nothing (no message), if radio button by default is true, and selected is true?

You can start a variable outside the event:
var radioChanged = 0;
And, in your event increase it:
$(':radio').change(function() {
radioChanged += 1;
// your code ...
});
Then, later on:
if (radioChanged > 0) {
alert('Change function occurred ' + radioChanged + ' times.');
} else {
alert('Radio button not changed.');
}

As i understand your expected behaviour, check if any radio has no more its default checked value:
$('form').on('submit', function() {
var anyRadioChanged = !!$(this).find('input[type="radio"]').filter(function() {
return $(this).is(':checked') != this.defaultChecked;
}).length; // '!!' to get boolean but it doesn't really matter here
if(anyRadioChanged) {
// show message(???)
}
})

you can hide message element just adding display: none to it or use jquery hide method
$('#someElementId').hide();
or
$('#someElementId').css("display","none")

Related

Get the certain radio button

have 5 radio button(yes or no) and I want to do is whenever I select 'Yes' either those buttons my textarea will color red, and I've already done that. but the problem is whenever I've select only one 'Yes' and change it to No the color of the textarea still remains on red
$('.com_lease_checkbox').on("change", function() {
console.log($(this).val());
$(".com_lease_checkbox:checked").each(function(){
// Check if the value is Yes
if ($(this).is(':checked') && $(this).val() == 'Yes') {
// Set the color of text-area
$('.com_lease_desc_a').css("border-color","red");
}
});
});
Simple way to do this is to Count How many selected 'No's .. if it's Zero it's OK else Red
$('.com_lease_checkbox').on("change", function() {
//var selectedYesCheckBoxesCount = $(".com_lease_checkbox[value='Yes']:selected").length;
var selectedNoCheckBoxesCount = $(".com_lease_checkbox[value='No']:selected").length;
if(selectedNoCheckBoxesCount > 0) {
$('.com_lease_desc_a').css("border-color","red");
}
else {
$('.com_lease_desc_a').css("border-color","green");
}
});

Having Button not run Function With Empty Input Field

So I have a button that whenever clicked appends whatever the user entered below the input field. I want to make it so when clicked with an empty field nothing appends (essentially the function does not run).
Here is my code:
var ingrCount = 0
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
var ingredientSpace = $("<p>");
ingredientSpace.attr("id", "ingredient-" + ingrCount);
ingredientSpace.append(" " + ingredientInput);
var ingrClose = $("<button>");
ingrClose.attr("data-ingr", ingrCount);
ingrClose.addClass("deleteBox");
ingrClose.append("✖︎");
// Append the button to the to do item
ingredientSpace = ingredientSpace.prepend(ingrClose);
// Add the button and ingredient to the div
$("#listOfIngr").append(ingredientSpace);
// Clear the textbox when done
$("#ingredients").val("");
// Add to the ingredient list
ingrCount++;
if (ingredientInput === "") {
}
});
So I wanted to create an if statement saying when the input is blank then the function does not run. I think I may need to move that out of the on click function though. For the if statement I added a disabled attribute and then removed it when the input box contains something. But that turns the button another color and is not the functionality I want. Any ideas I can test out would help. If you need any more information please ask.
If you're testing if ingredientInput is empty, can you just return from within the click event?
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if(ingredientInput === '') { return; }
// rest of code
Simply use :
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if (ingredientInput.length == 0) {
return false;
}
// ..... your code

jQuery problems with function

What i'm trying to do here is if the selection is equal to value 10 the click function to be available only if selection is equal to 10. But when i change to other ex. category with different value the radio click function is still available. ?
I have 6 radio boxes with value 1,2,3,4,5,6 so what i want to do if value == 4 to slidedown another div while i'm in category with value 10.(selection).
How can i fix this problem ? Here is my sample code.
$('#category').on('change', function () {
var selection = $(this).val();
$('#slidedown'+selection).slideDown(200);
if(selection == '10'){
$("input:radio[name='checkbox']").click(function() {
var radio = $(this).val();
if(radio == '4' && selection == '10') {
$('#slidedown'+selection).slideUp();
} else {
$('#slidedown'+selection).slideDown();
}
});
});
Thanks, any help will be appreciated.
EDIT : I want to slideUp the currect div which is slided down by the category value if radio box with value 4 is checked.
You should have another selection var inside the click callback:
$('#category').on('change', function () {
var selection = $(this).val();
$('#slidedown'+selection).slideDown(200);
});
$("input:radio[name='checkbox']").click(function() {
var selection = $('#category').val(); //This does the trick
var radio = $(this).val();
if(radio == '4' && selection == '10') {
$('#slidedown_another').slideUp();
} else {
$('#slidedown_another').slideDown();
}
});
Also, callbacks must be separated for not binding a new listener each time
Hope this helps. Cheers
Use the disabled property to enable and disable the radio buttons.
$('#category').change(function() {
var selection = $(this).val();
$('#slidedown'+selection).slideDown(200);
$('input:radio[name=checkbox]').prop('disabled', selection != '10');
});
$("input:radio[name='checkbox']").click(function() {
var radio = $(this).val();
if(radio == '4') {
$('#slidedown_another').slideUp();
} else {
$('#slidedown_another').slideDown();
}
});
Your code is adding a handler when the select has the correct value, but it never removes the handler when the select changes to a different value. Also, every time they select 10 it was adding another handler, so the handler would then run multiple times.

Show button if input is not empty

I am not much of a JavaScript guru, so I would need help with a simple code.
I have a button that clears the value of an input field.
I would like it (the button) to be hidden if input field is empty and vice versa (visible if there is text inside the input field).
The solution can be pure JavaScript or jQuery, it doesn't matter. The simpler, the better.
$("input").keyup(function () {
if ($(this).val()) {
$("button").show();
}
else {
$("button").hide();
}
});
$("button").click(function () {
$("input").val('');
$(this).hide();
});
http://jsfiddle.net/SVxbW/
if(!$('input').val()){
$('#button').hide();
}
else {
$('#button').show();
}
In it's simplest form ;)
to do this without jQuery (essentially the same thing others already did, just pure js). It's pretty simple, but I've also added a few comments.
<body>
<input type="text" id="YourTextBox" value="" />
<input type="button" id="YourButton" value="Click Me" />
<script type="text/javascript">
var textBox = null;
var button = null;
var textBox_Change = function(e) {
// just calls the function that sets the visibility
button_SetVisibility();
};
var button_SetVisibility = function() {
// simply check if the visibility is set to 'visible' AND textbox hasn't been filled
// if it's already visibile and the text is blank, hide it
if((button.style.visibility === 'visible') && (textBox.value === '')) {
button.style.visibility = 'hidden';
} else {
// show it otherwise
button.style.visibility = 'visible';
}
};
var button_Click = function(e) {
// absolutely not required, just to add more to the sample
// this will set the textbox to empty and call the function that sets the visibility
textBox.value = '';
button_SetVisibility();
};
// wrap the calls inside anonymous function
(function() {
// define the references for the textbox and button here
textBox = document.getElementById("YourTextBox");
button = document.getElementById("YourButton");
// some browsers start it off with empty, so we force it to be visible, that's why I'll be using only chrome for now on...
if('' === button.style.visibility) { button.style.visibility = 'visible'; }
// assign the event handlers for the change and click event
textBox.onchange = textBox_Change;
button.onclick = button_Click;
// initialize calling the function to set the button visibility
button_SetVisibility();
})();
</script>
</body>​
Note: I've written and tested this in IE9 and Chrome, make sure you test it in other browsers. Also, I've added this fiddle so you can see it working.
You can use $('selector').hide() to hide an element from view and $('selector').show() to display it again.
Even better, you can use $('selector').toggle() to have it show and hide without any custom logic.
First hide the button on page load:
jQuery(document).ready(function() {
jQuery("#myButton").hide();
});
Then attach an onChange handler, which will hide the button whenever the contents of the text-field are empty. Otherwise, it shows the button:
jQuery("#myText").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery("#myButton").hide();
} else {
jQuery("#myButton").show();
}
});
You will also need to hide the button after clearing the input:
jQuery("#myButton").click(function() {
jQuery("#myInput").val("");
jQuery(this).hide();
});

jQuery addClass doesnt work in IE 7 or IE 8

This is a validation script
This code runs when the user presses the submit button on a form
It loops thru all mandatory fields (entered in an array) and...
1. checks if the element is hidden
2. if not is it empty?
3. if not is it false? (I use false as a value for non selectable options)
And all this sets a variable to true or false.
// when submitting the registration form
function mandatoryCheck() {
jQuery('.tx-powermail-pi1_formwrap_1723 form.tx_powermail_pi1_form').submit(function(event) {
var success = false;
var element;
jQuery.each(mandatoryFields, function(index, value) {
element = jQuery('#powermaildiv_uid'+value+' input, #powermaildiv_uid'+value+' select')
element.each(function() {
// add class required to all fields
jQuery(this).addClass('required');
// is the element hidden, return true
if(jQuery(this).hasClass('fieldHidden') == true || jQuery(this).is(':disabled')) {
success = true;
} else {
// is the input field empty, return false
if(jQuery(this).val().length === 0) {
success = false;
// is the input field not empty, return true
} else {
// is the input field false, return false
if(jQuery(this).val() == 'disabled') {
success = false;
} else {
success = true;
}
}
}
// For each element add/remove validation class
if(success == false) {
jQuery(this).addClass('validation-failed').removeClass('validation-passed');
} else {
jQuery(this).addClass('validation-passed').removeClass('validation-failed');
}
});
});
// if succes is false, show error message and return false
if(success == false) {
jQuery('#c1799').fadeIn().css('display', 'block');
event.preventDefault();
return false;
} else {
jQuery('#c1799').fadeOut();
}
});
}
It works in firefox, chrome ie9 but not ie 7 or 8.
IE7 or 8 adds classes to the elements all random.
It seems like if I validate a select element it passes but an input field fails
What can be wrong?
Edit:
Here is the page: http://asdf.patrikelfstrom.se/index.php?id=267
Enter 1234 if in the little form that shows up
JS: http://asdf.patrikelfstrom.se/typo3conf/ext/gc_fm/res/js/ShowAndHideFields.js
If you press submit (absenden) the field Türnummer should be green (as it is in chrome, firefox etc.) but in ie7/8 it is red.
If you click on Wähle... (The select box) and choose Wohnung the fields under it becomes enabled and if you press submit now Türnummershould be red since the element is visible and empty.
This seems to work but if you click on the select box again and choose einfamilienhaus.
The fields are disabled and should now be green when submitting but this is not the case in IE7/8.
I think you need to loop through element, as it will be a collection of objects, so you would do...
// is the element hidden, return true
element.each(function() {
if($(this).hasClass('fieldHidden') == true) {
...
})
Well, just to show the point, depends on your code what you need to actually change
Remove the (value="false") from your selects.

Categories

Resources