Javascript/Wordpress - Form selection conditions - javascript

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>

Related

jQuery onChange only running once

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">

How to write simplified and generic validation logics and rules in JQuery

I know there are tons of information out there over internet to validate form in JavaScript and JQuery. But I’m interested to write my own. Basically I want to learn this thing.
So here is my validation script I have written and its working fine.
function validate() {
var firstName = jQuery("#firstName").val();
var lastName = jQuery("#lastName").val();
var dateOfBirthy = jQuery().val("dateOfBirth");
if (firstName.length == 0) {
addRemoveValidationCSSclass("#firstName", false);
} else {
addRemoveValidationCSSclass("#firstName", true);
}
if (lastName.length == 0) {
addRemoveValidationCSSclass("#lastName", false);
} else {
addRemoveValidationCSSclass("#lastName", true);
}
}
function addRemoveValidationCSSclass(inputField, isValid) {
var div = jQuery(inputField).parents("div.control-group");
if (isValid == false) {
div.removeClass("success");
div.addClass("error");
} else if (isValid == true) {
div.removeClass("error");
div.addClass("success");
} else {
}
}
I want to achieve few things--
add validation message
More generic way to handle for every form.
And I want to add validation rule, like length, email validation,
date validation etc.
Now how can I achieve these?
Use jQuery validate. It does everything you want straight out of the box.
I did something similar to this, except that I wrote my rules in PHP since you need a server-side backup. When the PHP generates the form, it also generates some simple client-side validation that looks like this:
<!-- html field -->
<label for="first">
First Name: <input type="text" name="first" id="first">
<span id="first_message"></span>
</label>
Then the script is like this:
<script>
var formValid = true;
var fieldValid = true;
// Check first name
fieldValid = doRequiredCheck("first");
if (!fieldValid) {formValid = false};
fieldValid = doCheckLength("first", 25);
if (!fieldValid) {formValid = false};
function doRequiredCheck(id) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value === "") {
box.innerHTML = "**REQUIRED**";
}
}
function doCheckLength(id,len) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value.length > len) {
box.innerHTML = "Too long";
}
}
</script>
Create a simple function:
function validations(day, hour, tap1, tap2, employed){
if( day== "" | hour== "" | tap1== "" | tap2== "" | employed== "" ){
return false;
} else {
return true;
}

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

More efficient way of writing this javascript

I am creating a contact form for my website and and using javascript to the first layer of validation before submitting it which is then checked again via php but i am relatively new to javascript, here is my script...
$("#send").click(function() {
var fullname = $("input#fullname").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
if (fullname == ""){
$("input#fullname").css("background","#d02624");
$("input#fullname").css("color","#121212");
}else{
$("input#fullname").css("background","#121212");
$("input#fullname").css("color","#5c5c5c");
}
if (email == ""){
$("input#email").css("background","#d02624");
$("input#email").css("color","#121212");
}else{
$("input#email").css("background","#121212");
$("input#email").css("color","#5c5c5c");
}
if (subject == ""){
$("input#subject").css("background","#d02624");
$("input#subject").css("color","#121212");
}else{
$("input#subject").css("background","#121212");
$("input#subject").css("color","#5c5c5c");
}
if (message == ""){
$("textarea#message").css("background","#d02624");
$("textarea#message").css("color","#121212");
}else{
$("textarea#message").css("background","#121212");
$("textarea#message").css("color","#5c5c5c");
}
if (name && email && subject && message != ""){
alert("YAY");
}
});
How can i write this more efficiently and make the alert show if all the fields are filled out, thanks.
$("#send").click(function() {
var failed = false;
$('input#fullname, input#email, input#subject, textarea#message').each(function() {
var item = $(this);
if (item.val()) {
item.css("background","#121212").css("color","#5c5c5c");
} else {
item.css("background","#d02624").css("color","#121212");
failed = true;
}
});
if (failed){
alert("YAY");
}
});
glavic and matt's answers were exactly what I was going to suggest, except I would take it a step further by separating the logic from the presentation.
Have classes defined in your css for when a field contains an invalid entry, and add or remove that class using $.addClass() or $.removeClass()
Since you're using jQuery, I would recommend setting a class on each field that requires a non-blank value (class="required").
Then you do something like this:
var foundEmpty = false;
$(".required").each(function()
{
if($(this).val())
{
foundEmpty=true;
$(this).style("background-color", "red");
}
});
if(foundEmpty)
{
alert("One or more fields require a value.");
}
Giving them a common class, define classes to apply the styles, and do this:
JS
$("#send").click(function() {
$('.validate').attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( $('.invalid').length === 0 ) {
alert('YAY');
}
});
CSS
.valid {
background:#121212;
color:#5c5c5c
}
.invalid {
background:#d02624;
color:#121212;
}
HTML
<button id="send">SEND</button><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate">
JSFIDDLE DEMO
A little bit more efficient approach:
var validate = $('.validate');
$("#send").click(function() {
validate.attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( validate.filter('.invalid').length === 0 ) {
alert('YAY');
}
});
You can use jQuery to iterate over each object and get their values. Depending on your form, this code will change, but it's to give you an example. I'm probably missing a couple of brackets here and there but the concept is there.
var objectName=$(this).attr('id');
$('#formId').children().each(
function(){
if ($(this).value == ""){
$(this).css("background","#d02624");
$(this).css("color","#121212");
$error[objectName]='true';
}else{
$(this).css("background","#121212");
$(this).css("color","#5c5c5c");
$error[objectName]='false';
}
}
);
$.each(error, function(key, value){
if (value=='false'){
alert (key + 'is empty');
}
});
I would probably divide part of this up into my css file. If any of the fields are empty add a class like "empty" to the object, if not, remove it. Then in your css file you can add some descriptors like:
input#fullname,
input#email {
...
}
input#fullname.empty,
input#email.empty {
...
}
You can use jQuery addClass() and removeClass().
You can then add a loop as follows:
var inputs = new Array();
inputs[0] = "input#fullname";
inputs[1] = "input#email";
inputs[2] = "input#subject";
inputs[3] = "textarea#message";
var complete = true;
for (var i = 0; i < 4; i++) {
var value = $(inputs[0]).val();
if (value.length > 0) {
$(inputs[i]).removeClass("empty");
} else {
complete = false;
$(inputs[i]).addClass("empty");
}
}
if (complete) {
}
EDIT:
There you go, fixed it for you.

Input text form, using javascript to clear and restore form contents problem

I have this line of HTML
<input type="text" name="addQty" size="1"
class="addQty" value="0"
onclick="$(this).val('')"
onblur="itmQtyChk($(this).val())" />
the itmQtyChk function does this:
function itmQtyChk( qty ) {
if( qty == "") {
$(this).val("0");
} else {
$(this).val(qty);
}
}
My problem is I want it to return the original value to the input text if they exit the field and don't change anything, but it is not working.
Thank you for any help.
this in itmQtyChk function is not referring to the input but to the window object.
Change the function to accept the input as parameter:
function itmQtyChk(input) {
if (input.val() == "") {
input.val("0");
}
// the else part is not needed
}
with the onblur event also:
onblur="itmQtyChk($(this))"
Check this fiddle, it has lots of room for improvement, but it can help you:
http://jsfiddle.net/eDuKr/1/
$(function(){
var cacheQty;
$('.addQty').click(function(){
cacheQty = $(this).val();
$(this).val('');
}).blur(function(){
if ($(this).val() === ''){
$(this).val(cacheQty);
}else{
cacheQty = $(this).val();
}
});
});

Categories

Resources