Getting default value of radio button upon page load using jQuery - javascript

I have two radio buttons whom I set to default (first selected value radio button is the default one upon load) like following:
var listing_type;
var shipping_location;
$(":radio[name='type'][value='1']").attr('checked', 'checked');
$(":radio[name='shipping'][value='1']").attr('checked', 'checked');
When the user clicks on some of the values from radio buttons, the values are caught like following:
$('input:radio[name=type]').click(function () {
listing_type = $(this).val();
});
$('input:radio[name=shipping]').click(function () {
shipping_location = $(this).val();
});
This 2nd part of the code works just fine, when the user clicks on some of the radio buttons, values are passed into my MVC Action just correctly.
However, I'm unable to catch the value if the user doesn't clicks anything on the radio buttons (i.e. leaves them as default as they are upon page load) and clicks "Search" Button...
The values in my MVC Action are always null for some reason, even though they aren't supposed to be. Here is how I'm passing the values and the here is the C# code from the Action:
$.post("/Search/Index", { keywords: $('.txtSearch').val(), type: /* listing_type */ <=> $('input[name=type]:checked').val(), location: $('input[name=shipping]:checked').val() <=> /*shipping_location*/ }, StartLoading())
.done(function (data) {
StopLoading();
var brands = $('<table />').append(data).find('#tableProducts').html();
$('#tableProducts').html(brands);
$('#tableProducts thead').show();
});
}
And this is the Action:
public ActionResult Index(string keywords, string type, string location)
{
// If the user doesn't interacts with the radio buttons and just enters the search term (ie. keywords) the type and location variables are null).
if ((keywords != null && keywords != "") && (type != null && type != "") && (location != null && location!=""))
{
// do something here....
}
return View();
}
So now my question is:
How can I pass the default values from the radio buttons if the user doesn't interacts with them (i.e. passing the default values I've set upon page load)???

Give this a try:
$('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);
$('input:radio[name="shipping"]').filter('[value="1"]').attr('checked', true);

Related

Multiple Javascript Event Listener Issues

Background info: I'm using WooCommerce and Gravity Forms, and trying to make it so the Add to Cart button is inactive according to two conditions - either there are no attendees registered, or the date hasn't been selected from the product variation dropdown. The user should only be able to move forward if both sections are completed.
The Gravity Forms component of this has a popup module to sign up those attendees, but the summary is displayed outside the module and on the main product page. The class .gpnf-no-entries lives on the "outside" of the Gravity Forms module, since it's always visible on the page. .gpnf-nested-entries and .gpnf-row-actions are also outside the module, but rely on information from within the module. .tingle-btn is a class used on multiple buttons inside the module - to add an attendee, cancel editing, or delete that attendee (unsure if I need a loop on here - alerts were working without one, and it seems like there's something else causing issues regardless).
Issues: It was working at one point, but only after the second click (anywhere on the page). There's also a second issue - on this form, if you've added an attendee but not added the product to the cart, the page retains any info you've put in. So what happens is, if you refresh the page and have old attendee info already there, the Add to Cart never gets clickable after selecting a date, even though both areas are filled out.
Screenshots:
I'm still somewhat of a beginner here so it's quite possibly something silly.
<script>
var modalButtons = document.querySelectorAll('.tingle-btn');
var noEntries = document.querySelector('.gform_body .gpnf-no-entries');
var entryField = document.querySelectorAll(".gpnf-nested-entries .entry-field[style='display: block;']");
var nestedEntriesDelete = document.querySelector('.gpnf-row-actions .delete');
var addToCart = document.querySelector('.single_add_to_cart_button');
var wcVariation = document.querySelector('.woocommerce-variation-add-to-cart');
var selectCheck = document.querySelector('#select-date-option');
//When date selection dropdown is changed, check value and check for "no entries" message
document.addEventListener('change', function (event) {
if (!event.target.matches('selectCheck')) {
if ((noEntries.style.display !== 'none') || (selectCheck.value === '')) {
addToCart.classList.add('disabled');
wcVariation.classList.remove('woocommerce-variation-add-to-cart-enabled');
wcVariation.classList.add('woocommerce-variation-add-to-cart-disabled');
}
else {
addToCart.classList.remove('disabled');
wcVariation.classList.add('woocommerce-variation-add-to-cart-enabled');
wcVariation.classList.remove('woocommerce-variation-add-to-cart-disabled');
}
}
}, false);
// When attendee is deleted, check to see if there are any entry fields left
document.addEventListener('click', function (event) {
if (!event.target.matches('nestedEntriesDelete')) {
if (entryField.length <= 3) {
addToCart.classList.add('disabled');
wcVariation.classList.remove('woocommerce-variation-add-to-cart-enabled');
wcVariation.classList.add('woocommerce-variation-add-to-cart-disabled');
}
}
}, false);
// Check for "no entries" and no date selection value when buttons to add or remove attendees are clicked
document.addEventListener('click', function (event) {
if (!event.target.matches('modalButtons')) {
if ((noEntries.style.display !== 'none') || (selectCheck.value === '')) {
addToCart.classList.add('disabled');
wcVariation.classList.remove('woocommerce-variation-add-to-cart-enabled');
wcVariation.classList.add('woocommerce-variation-add-to-cart-disabled');
}
else {
addToCart.classList.remove('disabled');
wcVariation.classList.add('woocommerce-variation-add-to-cart-enabled');
wcVariation.classList.remove('woocommerce-variation-add-to-cart-disabled');
}
}
}, false);
</script>
I ended up doing this a much simpler way by adding classes:
<script>
var noEntries = document.querySelector('.gform_body .gpnf-no-entries');
var entriesContainer = document.querySelector('.gpnf-nested-entries-container');
var addToCart = document.querySelector('.single_add_to_cart_button');
//When page is fully loaded, check for cached entries
window.addEventListener('load', function () {
//if there are entries, show the add to cart button
if (noEntries.style.display === 'none'){
entriesContainer.classList.add('has-entries');
addToCart.classList.add('do-add');
addToCart.classList.remove('dont-add');
}
//if there are no entries, disable the add to cart button
else if (noEntries.style.display === ''){
entriesContainer.classList.remove('has-entries');
addToCart.classList.add('dont-add');
addToCart.classList.remove('do-add');
}
//if the form isn't present, don't do any of this
else if (noEntries = 'null'){
//do nothing
}
});
//When the container with the form and the entries is clicked, check for entries
document.addEventListener('click', function (event) {
if (!event.target.matches('#gform_wrapper_41')) {
setInterval(function() {
//if an entry is added, show the add to cart button
if (noEntries.style.display === 'none'){
entriesContainer.classList.add('has-entries');
addToCart.classList.add('do-add');
addToCart.classList.remove('dont-add');
}
//if all entries are removed, disable the add to cart button
else if (noEntries.style.display === ''){
entriesContainer.classList.remove('has-entries');
addToCart.classList.add('dont-add');
addToCart.classList.remove('do-add');
}
},2000);
}
}, false);
</script>

Post dropdownlistfor model binding without reloading page

I have a "dynamic" page which contains a dropdownlistfor. When I select a value from the dropdown, the page, without redirecting, hides the old div which contained the old dropdown, and displays a new div (using JS .show() function) with a new dropdown that pulls data based on the value of the old dropdown.
My issue is that I don't know how to POST the value of the first dropdown to it's model without redirecting or reloading the page. I have tried this:
$('#binRange_start_form').submit(function(event) {
event.preventDefault();
$(this).submit();
});
Which doesn't call the setter function of my field in my model:
private String _BinRangeSelection;
public String BinRangeSelection
{
get
{
return _BinRangeSelection;
}
set
{
System.Diagnostics.Debug.WriteLine("testing");
string[] rangeSplit = Regex.Split(value, " - ");
foreach (IdentifiBINConfiguration ibc in IdentifiBINConfigs)
{
if (ibc.LowerRange == rangeSplit[0] && ibc.UpperRange == rangeSplit[1])
{
IdentifiBINConfiguration = ibc;
}
}
_BinRangeSelection = value;
}
}
And it also reloads the page.

How to test if users has made any changes to a form if they haven't saved it

Basically the same functionality as stackoverflow when posting a question, if you start writing a post then try to reload the page. You get a javascript alert box warning message.
I understand how to check if the form has been changed, although how do I do the next step.
I.E: How to I check this when leaving the page, on here you get "This page is asking you to confirm that you want to leave - data you have entered may not be saved."?
EDIT: found correct answer here to another question https://stackoverflow.com/a/2366024/560287
I'm very sure that if you search, 'jQuery detect form change plugin', you will find something much more usable than this semi-pseudo code i'm about to write:
formChanged = function(form) {
form.find('input[type="text"], textarea').each(function(elem) {
if (elem.defaultValue != elem.value) {
return true;
}
});
// repeat for checkbox/radio: .defaultChecked
// repeat for ddl/listbox: .defaultSelected
return false;
}
usage:
if (formChanged($('form')) { // do something }
Note that this is to detect changes against the original rendered value. For instance, if a textbox has a value = "x", and the user changes it to "y", then changes it back to "x"; this will detect it as NO change.
If you do not care about this scenario, you can just do this:
window.formChanged = false;
$(':input').change(function() {
window.formChanged = true;
});
Then you can just check that value.
Yes, it is JavaScript as HTML is just a markup language.
Yes, jQuery can be used for this. It's preferable over vanilla JavaScript as it makes things easier, although it does add some overhead.
There are a number of ways to check if any of a form's controls have changed.
To check for changes from the default, most can be checked against the defaultValue property. For radio buttons, you should always have one checked by default, so check if it's still selected or not. Similarly for selects, set the selected attribute for the default option and see if it's still selected, and so on.
Alternatively, if all your form controls have an ID or unique name, you can collect all their values onload and then check their values when the form is submitted.
Another method is to listen for change events on each form control, but that is a bit over the top.
Here's a POJS version that takes the same approach as rkw's answer:
/*
Check if any control in a form has changed from its default value.
Checks against the default value for inputs and textareas,
defaultChecked for radio buttons and checkboxes, and
default selected for select (option) elements.
*/
function formChanged(form) {
var control, controls = form.elements;
var tagName, type;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
tagName = control.tagName.toLowerCase();
type = control.type;
// textarea
if (tagName == 'textarea') {
if (control.value != control.defaultValue) {
return true;
}
// input
} else if (tagName == 'input') {
// text
if (type == 'text') {
if (control.value != control.defaultValue) {
return true;
}
// radio and checkbox
} else if (type == 'radio' || type == 'checkbox') {
if (control.checked != control.defaultChecked) {
return true;
}
}
// select multiple and single
} else if (tagName == 'select') {
var option, options = control.options;
for (var j=0, jLen=options.length; j<jLen; j++) {
option = options[j];
if (option.selected != option.defaultSelected) {
return true;
}
}
}
}
// Not really needed, but some like the return value to
// be a consistent Type
return false;
}
Note that you need to be careful with select elements. For a single select, you should always set one option to selected, as if there is no default selected, some browsers will make the first option selected and others wont.

Disabling/enabling a button based on multiple other controls using Javascript/jQuery

I have a bunch of controls:
When a user clicks the Generate button, a function uses all of the values from the other controls to generate a string which is then put in the Tag text box.
All of the other controls can have a value of null or empty string. The requirement is that if ANY of the controls have no user entered value then the Generate button is disabled. Once ALL the controls have a valid value, then the Generate button is enabled.
What is the best way to perform this using Javascript/jQuery?
This can be further optimized, but should get you started:
var pass = true;
$('select, input').each(function(){
if ( ! ( $(this).val() || $(this).find(':selected').val() ) ) {
$(this).focus();
pass = false;
return false;
}
});
if (pass) {
// run your generate function
}
http://jsfiddle.net/ZUg4Z/
Note: Don't use this: if ( ! ( $(this).val() || $(this).find(':selected').val() ) ).
It's just for illustration purposes.
This code assumes that all the form fields have a default value of the empty string.
$('selector_for_the_parent_form')
.bind('focus blur click change', function(e){
var
$generate = $('selector_for_the_generate_button');
$generate.removeAttr('disabled');
$(this)
.find('input[type=text], select')
.each(function(index, elem){
if (!$(elem).val()) {
$generate.attr('disabled', 'disabled');
}
});
});
Basically, whenever an event bubbles up to the form that might have affected whether the generate button ought to be displayed, test whether any inputs have empty values. If any do, then disable the button.
Disclaimer: I have not tested the code above, just wrote it in one pass.
If you want the Generate button to be enabled as soon as the user presses a key, then you probably want to capture the keypress event on each input and the change event on each select box. The handlers could all point to one method that enables/disables the Generate button.
function updateGenerateButton() {
if (isAnyInputEmpty()) {
$("#generateButton").attr("disabled", "disabled");
} else {
$("#generateButton").removeAttr("disabled");
}
}
function isAnyInputEmpty() {
var isEmpty = false;
$("#input1, #input2, #select1, #select2").each(function() {
if ($(this).val().length <= 0) {
isEmpty = true;
}
});
return isEmpty;
}
$("#input1, #input2").keypress(updateGenerateButton);
$("#select1, #select2").change(updateGenerateButton);
The above assumes that your input tags have "id" attributes like input1 and select2.

Enabling 'Save' Button on index change

I have a popup with 1 dropdown list (mandatory), 1 datepicker (mandatory) & 1 textbox (optional). I am checking in 1st two that if they both contain any data and then I am enabling the 'Save' button.
However, if the user already has some dropdown item in it and date picked then also, the 'Save' button is enabled. I dont want this. So the logic here is:
Check the dropdown list and datepicker
If they both contain item in it & item has been changed then enable
the 'Save' button.
Else, disable the button.
Here is my code:
function EnableSaveButton() {
var tempDDL = jQuery("#testPopup SELECT");
var tempText = jQuery("#testPopup INPUT:text");
var buttons = jQuery("#testPopup INPUT:button");
jQuery.each(buttons, function (i, buttonCtl) {
if (buttonCtl.value.toLowerCase() == "save") {
if ((tempDDL.find('OPTION:selected').val() !== "-1") && (tempText.val() != ""))
buttonCtl.disabled = false;
else
buttonCtl.disabled = true;
}
});
}
Keep track of the dropdown selection on page load and after saves.
var ddlSelection = $('#testPopup select option:selected').val();
When the dropdown changes, check that the current selection is different.
if(tempDDL.find('OPTION:selected').val() !== ddlSelection)
If it is different enable the save button. On a save, update the dropdown selection variable.
ddlSelection = tempDDL.find('OPTION:selected').val()

Categories