jQuery onChange only running once - javascript

I have jQuery function in a Wordpress Woo form that basically based on the dropdown fills in certain fields, the jQuery only executes once however.
The code:
jQuery(document).ready(function() {
// Your code in here
jQuery(document).on('change', '#billing_complex_name', function() {
myFunc();
})
function myFunc() {
// your function code
var complex_name = jQuery('#billing_complex_name').val();
var suburb = jQuery('#billing_suburb').val();
if (complex_name == 'eldogleneast') {
jQuery("#billing_suburb").val('ELD');
jQuery('#billing_postcode').val('0157');
} else if (complex_name == 'Reldoglen') {
jQuery("#billing_suburb").val('LPN');
jQuery('#billing_postcode').val('0133');
} else if (complex_name == 'eldin') {
jQuery("#billing_suburb").val('STK');
jQuery('#billing_postcode').val('2147');
jQuery("#billing_complex_address").val('Lion St');
} else if (complex_name == 'elm') {
jQuery("#billing_suburb").val('ELD');
jQuery('#billing_postcode').val('0147');
jQuery("#billing_complex_address").val('Lor Ave');
}
}
})
How do I get it to always run onChange not just the once.

If 1st time select working and 2nd time not then need to reset value of select on mouseenter event like in my snippet code.
Don't need to write document ready statement For both static and dynamic select changes.
Something like this.
jQuery(document).on('change', 'select', function (e) {
// do something
});
I hope below snippet will help you a lot.
function myFunc(getvalue) {
var complex_name = getvalue;
if (complex_name == 'eldogleneast') {
jQuery("#billing_suburb").val('ELD');
jQuery('#billing_postcode').val('0157');
} else if (complex_name == 'Reldoglen') {
jQuery("#billing_suburb").val('LPN');
jQuery('#billing_postcode').val('0133');
} else if (complex_name == 'eldin') {
jQuery("#billing_suburb").val('STK');
jQuery('#billing_postcode').val('2147');
jQuery("#billing_complex_address").val('Lion St');
} else if (complex_name == 'elm') {
jQuery("#billing_suburb").val('ELD');
jQuery('#billing_postcode').val('0147');
jQuery("#billing_complex_address").val('Lor Ave');
}
}
jQuery(document).on('change', '#billing_complex_name', function () {
var getname = jQuery('#billing_complex_name').val();
jQuery("#billing_suburb, #billing_postcode, #billing_complex_address").val('')// first reset
myFunc(getname);
});
jQuery(document).on('mouseenter', '#billing_complex_name', function () {
$(this).val(''); // need to reset after change
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="billing_complex_name">
<option value="" selected>---</option>
<option value="eldogleneast">eldogleneast</option>
<option value="Reldoglen">Reldoglen</option>
<option value="eldin">eldin</option>
<option value="elm">elm</option>
</select>
<br><br>
<label>Suburb</label><br>
<input type="text" id="billing_suburb">
<br><br>
<label>Post Code</label><br>
<input type="text" id="billing_postcode">
<br><br>
<label>Address</label><br>
<input type="text" id="billing_complex_address">

Related

if checkbox check but input empty disable another checkbox

i have one chekbox and one textfield
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<input class="form-control" type="text" id="usr_zipcode" maxlength="10" name="usr_zipcode" required="required">
how to make jquery, when vehiche1 is check but usr_zipcode is empty or no value, it disable another checkbox , name checkme :
<input type="checkbox" id="checkme">
i try to use below code but not working
$('#vehicle1').change(function () {
var input1 = $('#usr_zipcode');
input1.change( function() {
var empty = ( input1.val() == '' );
$("#checkme").prop('checked', false);
$("#checkme").attr('disabled','disabled');
});
}).change();
create a separate function to check or disable another checkbox like below
function checkOrDisableAnotherCheckBox() {
if($('#vehicle1').is(':checked') && $('#usr_zipcode').val() == ''){
$("#checkme").attr('disabled', true);
} else {
$("#checkme").removeAttr('disabled');
}
}
$('#vehicle1').change(function () {
checkOrDisableAnotherCheckBox();
});
$('#usr_zipcode').keyup(function () {
checkOrDisableAnotherCheckBox();
});
You can try my code:
$('#vehicle1').change(function () {
checkEmpty();
});
function checkEmpty(){
var empty = ( $('#vehicle1').prop('checked') && $('#usr_zipcode').val() == '' );
if (empty) {
$("#checkme").prop('checked', false);
$("#checkme").attr('disabled','disabled');
}else {
$("#checkme").removeAttr("disabled");
}
}
This is a demo: https://codepen.io/phuongnm153/pen/zQavrN

Change a requiered value from input with jquery or javascript

I need to change the required value from a input base on a check box selection, here is what I have so far.... thanks
<input type="checkbox" id="no_land_line" name="no_land_line" value="”/> // if no land line check here
<script>
$(document).ready(function () {
$('#no_land_line').change(function () {
if (!this.checked)
{
$('#no_land_line_div').fadeOut('slow');
document.getElementById("land_line").setAttribute("required", true);
document.getElementById("cellphone").setAttribute("required", false);
}
else {
document.getElementById("land_line").setAttribute("required", false);
document.getElementById("cellphone").setAttribute("required", true);
$('#no_land_line_div').fadeIn('slow');
}
});
});
</script>
<input type="text" name="land_line" id="land_line" required="true"/> // landline number
<input type="tel" name="cellphone" id="cellphone" required="false"/> // cellphone number
<div id="no_land_line_div”>some text</div>
UPDATE WITH A WORKING CODE
required is not a javascript property.
Change
getElementById("land_line").required = false,
getElementById("cellphone").required = true;
to
$("#land_line").attr("required",false);
$("#cellphone").attr("required",true);
Here's the entire script code :
$(document).ready(function () {
$('#no_land_line').change(function () {
if (!this.checked)
{
$('#no_land_line_div').fadeOut('slow'),
$("#land_line").attr("required",false);
$("#cellphone").attr("required",true);
}
else {
$('#no_land_line_div').fadeIn('slow'),
$("#land_line").attr("required",true);
$("#cellphone").attr("required",false);
}
});
});
Working example : https://jsfiddle.net/23rdtjwq/4/
Following your use of javascript:
document.getElementById("land_line").setAttribute("required", false);
document.getElementById("cellphone").setAttribute("required", true);

Javascript/Wordpress - Form selection conditions

Javascript newbie here. I've got the following partially working code:
jQuery(document).ready(function ($) {
$("#frm_form_70_container input[type=submit]").css('visibility', 'hidden'); //hide submit button by default
$("select[name='item_meta[4418]'], select[name='item_meta[4473]'], select[name='item_meta[4474]'], select[name='item_meta[4483]']").change(function () {
var submit = true;
if ($("select[name='item_meta[4418]']:selected").val() == 'Email' || $("select[name='item_meta[4473]']:selected").val() == 'Email' || $("select[name='item_meta[4474]']:selected").val() == 'Email' || $("select[name='item_meta[4483]']:selected").val() == 'Email')
submit = false;
if (submit) {
$("#frm_form_70_container input[type=submit]").css('visibility', 'visible');
} else {
$("#frm_form_70_container input[type=submit]").css('visibility', 'hidden');
}
});
});
I've got a drop down box with a few values. What I want to happen is for the submit button to hide when anything other than the value "Email" is selected.
This probably seems foolish and I apologize, but any help would be appreciated.
Courtesy of mainly #smerny and myself
jQuery(document).ready(function ($) {
var $allSelects = $("#frm_form_70_container").find('select'),
$submitBtn = $("#frm_form_70_container input[type=submit]");
$allSelects.on('change', function () {
if (!$allSelects.filter(function() {
return this.value === "Email"; }).length) {
$submitBtn.hide();
} else {
$submitBtn.show();
}
});
});
Fiddle Demo
I've taken the code that #dcodesmith and #smerny suggested but I need to add another option like " return this.value === "Apply for Senior Forecaster";" see here: http://jsfiddle.net/2oajog5x/
I'm not that familiar with JS unfortunately.
jQuery(document).ready(function($) {
var $allSelects = $("#frm_form_11_container").find('select'),
$submitBtn = $("#frm_form_11_container input[type=submit]");
$allSelects.change(function() {
if (!$allSelects.filter(function() {
return this.value === "Apply for Senior Forecaster";
}).length) {
$submitBtn.hide();
} else {
$submitBtn.show();
}
});
});
.hide {
display: none;
}
<form id='frm_form_11_container'>
<select>
<option value="What do you want to do?">What do you want to do?</option>
<option value="Apply for Senior Forecaster">Apply for Senior Forecaster</option>
<option value="I'd like to talk about a position">I'd like to talk about a position</option>
</select>

JS: default text swap with live new element added

So for default text swapping on input (or other type of el) I have this snippet
<input class="js_text_swap" type="text" value="Enter your email" />
if($('.js_text_swap').length > 0) {
$('.js_text_swap').each(function() {
var that = $(this),
value = that.val(); // remembering the default value
that.focusin(function() {
if(that.val() === value) {
that.val('');
}
});
that.focusout(function() {
if(that.val() === '') {
that.val(value);
}
});
});
}
So my questions are:
1) does anybody has a better solution for this?
2) does anyone know how to make this work with live added elements (added with js after page has loaded)?
Thanks
Jap!
HTML
<input placeholder="Click..." class="text" type="text">
CSS
.text{color:#aaa}
.text.focus{color:#444}
JS
$("input[placeholder]").each(function() {
var placeholder = $(this).attr("placeholder");
$(this).val(placeholder).focus(function() {
if ($(this).val() == placeholder) {
$(this).val("").addClass('focus');
}
}).blur(function() {
if ($(this).val() === "") {
$(this).val(placeholder).removeClass('focus');
}
});
});
http://yckart.com/jquery-simple-placeholder/
UPDATE
To make it work with ajax or similar you need to convert it into a "plugin" and call it after your succesed ajax request (or after dynamically crap creating).
Something like this (very simple example):
jQuery.fn.placeholder = function() {
return this.each(function() {
var placeholder = $(this).attr("placeholder");
$(this).val(placeholder).focus(function() {
if ($(this).val() == placeholder) {
$(this).val("").addClass('focus');
}
}).blur(function() {
if ($(this).val() === "") {
$(this).val(placeholder).removeClass('focus');
}
});
});
};
$("input:text, textarea").placeholder();
$("button").on("click", function() {
$(this).before('<input type="text" placeholder="default value" />');
$("input:text, textarea").placeholder();
});
demo

How do you handle a form change in jQuery?

In jQuery, is there a simple way to test if any of a form's elements have changed?
Say I have a form and I have a button with the following click() event:
$('#mybutton').click(function() {
// Here is where is need to test
if(/* FORM has changed */) {
// Do something
}
});
How would I test if the form has changed since it was loaded?
You can do this:
$("form :input").change(function() {
$(this).closest('form').data('changed', true);
});
$('#mybutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
This rigs a change event handler to inputs in the form, if any of them change it uses .data() to set a changed value to true, then we just check for that value on the click, this assumes that #mybutton is inside the form (if not just replace $(this).closest('form') with $('#myForm')), but you could make it even more generic, like this:
$('.checkChangedbutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
References: Updated
According to jQuery this is a filter to select all form controls.
http://api.jquery.com/input-selector/
The :input selector basically selects all form controls.
If you want to check if the form data, as it is going to be sent to the server, have changed, you can serialize the form data on page load and compare it to the current form data:
$(function() {
var form_original_data = $("#myform").serialize();
$("#mybutton").click(function() {
if ($("#myform").serialize() != form_original_data) {
// Something changed
}
});
});
A real time and simple solution:
$('form').on('keyup change paste', 'input, select, textarea', function(){
console.log('Form changed!');
});
You can use multiple selectors to attach a callback to the change event for any form element.
$("input, select").change(function(){
// Something changed
});
EDIT
Since you mentioned you only need this for a click, you can simply modify my original code to this:
$("input, select").click(function(){
// A form element was clicked
});
EDIT #2
Ok, you can set a global that is set once something has been changed like this:
var FORM_HAS_CHANGED = false;
$('#mybutton').click(function() {
if (FORM_HAS_CHANGED) {
// The form has changed
}
});
$("input, select").change(function(){
FORM_HAS_CHANGED = true;
});
Looking at the updated question try something like
$('input, textarea, select').each(function(){
$(this).data("val", $(this).val());
});
$('#button').click(function() {
$('input, textarea, select').each(function(){
if($(this).data("val")!==$(this).val()) alert("Things Changed");
});
});
For the original question use something like
$('input').change(function() {
alert("Things have changed!");
});
$('form :input').change(function() {
// Something has changed
});
Here is an elegant solution.
There is hidden property for each input element on the form that you can use to determine whether or not the value was changed.
Each type of input has it's own property name. For example
for text/textarea it's defaultValue
for select it's defaultSelect
for checkbox/radio it's defaultChecked
Here is the example.
function bindFormChange($form) {
function touchButtons() {
var
changed_objects = [],
$observable_buttons = $form.find('input[type="submit"], button[type="submit"], button[data-object="reset-form"]');
changed_objects = $('input:text, input:checkbox, input:radio, textarea, select', $form).map(function () {
var
$input = $(this),
changed = false;
if ($input.is('input:text') || $input.is('textarea') ) {
changed = (($input).prop('defaultValue') != $input.val());
}
if (!changed && $input.is('select') ) {
changed = !$('option:selected', $input).prop('defaultSelected');
}
if (!changed && $input.is('input:checkbox') || $input.is('input:radio') ) {
changed = (($input).prop('defaultChecked') != $input.is(':checked'));
}
if (changed) {
return $input.attr('id');
}
}).toArray();
if (changed_objects.length) {
$observable_buttons.removeAttr('disabled')
} else {
$observable_buttons.attr('disabled', 'disabled');
}
};
touchButtons();
$('input, textarea, select', $form).each(function () {
var $input = $(this);
$input.on('keyup change', function () {
touchButtons();
});
});
};
Now just loop thru the forms on the page and you should see submit buttons disabled by default and they will be activated ONLY if you indeed will change some input value on the form.
$('form').each(function () {
bindFormChange($(this));
});
Implementation as a jQuery plugin is here https://github.com/kulbida/jmodifiable
var formStr = JSON.stringify($("#form").serializeArray());
...
function Submit(){
var newformStr = JSON.stringify($("#form").serializeArray());
if (formStr != newformStr){
...
formChangedfunct();
...
}
else {
...
formUnchangedfunct();
...
}
}
You need jQuery Form Observe plugin. That's what you are looking for.
Extending Udi's answer, this only checks on form submission, not on every input change.
$(document).ready( function () {
var form_data = $('#myform').serialize();
$('#myform').submit(function () {
if ( form_data == $(this).serialize() ) {
alert('no change');
} else {
alert('change');
}
});
});
$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
$("#result").html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Form "your_form_name"</h2>
<form name="your_form_name">
<input type="text" name="one_a" id="one_a" value="AAAAAAAA" />
<input type="text" name="one_b" id="one_b" value="BBBBBBBB" />
<input type="text" name="one_c" id="one_c" value="CCCCCCCC" />
<select name="one_d">
<option value="111111">111111</option>
<option value="222222">222222</option>
<option value="333333">333333</option>
</select>
</form>
<hr/>
<h2>Form "your_other_form_name"</h2>
<form name="your_other_form_name">
<input type="text" name="two_a" id="two_a" value="DDDDDDDD" />
<input type="text" name="two_b" id="two_b" value="EEEEEEEE" />
<input type="text" name="two_c" id="two_c" value="FFFFFFFF" />
<input type="text" name="two_d" id="two_d" value="GGGGGGGG" />
<input type="text" name="two_e" id="two_f" value="HHHHHHHH" />
<input type="text" name="two_f" id="two_e" value="IIIIIIII" />
<select name="two_g">
<option value="444444">444444</option>
<option value="555555">555555</option>
<option value="666666">666666</option>
</select>
</form>
<h2>Result</h2>
<div id="result">
<h2>Click on a field..</h2>
</div>
In addition to above #JoeD's answer.
If you want to target fields in a particular form (assuming there are more than one forms) than just fields, you can use the following code:
$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
// A form element was clicked
});
Try this:
<script>
var form_original_data = $("form").serialize();
var form_submit=false;
$('[type="submit"]').click(function() {
form_submit=true;
});
window.onbeforeunload = function() {
//console.log($("form").submit());
if ($("form").serialize() != form_original_data && form_submit==false) {
return "Do you really want to leave without saving?";
}
};
</script>
First, I'd add a hidden input to your form to track the state of the form. Then, I'd use this jQuery snippet to set the value of the hidden input when something on the form changes:
$("form")
.find("input")
.change(function(){
if ($("#hdnFormChanged").val() == "no")
{
$("#hdnFormChanged").val("yes");
}
});
When your button is clicked, you can check the state of your hidden input:
$("#Button").click(function(){
if($("#hdnFormChanged").val() == "yes")
{
// handler code here...
}
});

Categories

Resources