Disable an input field if second input (most current) field is filled - javascript

I'm very new to javascript. I read this link and tried to customize it but it is not working: Disable an input field if second input field is filled
I want to allow people to toggle between two options-city and zipcode. I want to enable whatever field they chose last and disable the other. For example, if they are on the zipcode tab and press the submit button, whatever input it is in the zipcode gets submitted and not the city & vice versa.
The html is:
<ul class="tabs">
<li><a class="border-radius top med" href="#city">City</a></li>
<li><a class="border-radius top med" href="#zipcode">Zipcode</a></li>
</ul>
<div id="city"><label class="IDX-advancedText">City</label>
<select id="aht-home-city" name="city[]" class="IDX-select " autocomplete="off">
<option value="2115">Austin</option>
<option value="2718">Bartlett</option>
</div>
<div id="zipcode"><label class="IDX-advancedText">Zipcode</label>
<input class="IDX-advancedBox IDX-advWildText" id="IDX-aw_zipcode" type="text"
maxlength="255" name="aw_zipcode" value="" /></div>
The script is:
var dis1 = document.getElementById("city");
dis1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("zipcode").disabled = true;
}
}
var dis2 = document.getElementById("zipcode");
dis1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("city").disabled = true;
}
}
Any help is very much appreciated! The website is http://austinhometeam.staging.wpengine.com/joyce-newsletter/

Like I told you in the comment, you need to change the ID in the "getElementById".
I also add the re-enabled the field when the other one is empty.
I add an empty value in the select, when the null is selected, the zip code's field return enable.
HTML
<ul class="tabs">
<li><a class="border-radius top med" href="#city">City</a></li>
<li><a class="border-radius top med" href="#zipcode">Zipcode</a></li>
</ul>
<div id="city"><label class="IDX-advancedText">City</label>
<select id="aht-home-city" name="city[]" class="IDX-select " autocomplete="off">
<option value=""></option>
<option value="2115">Austin</option>
<option value="2718">Bartlett</option>
</select>
</div>
<div id="zipcode"><label class="IDX-advancedText">Zipcode</label>
<input class="IDX-advancedBox IDX-advWildText" id="IDX-aw_zipcode" type="text"
maxlength="255" name="aw_zipcode" value="" /></div>
Javascript :
var dis1 = document.getElementById("aht-home-city");
var dis2 = document.getElementById("IDX-aw_zipcode");
dis1.onchange = function () {
if (dis1.value !== "" || dis1.value.length > 0) {
dis2.disabled = true;
} else {
dis2.disabled = false;
}
};
dis2.onchange = function () {
if (dis2.value !== "" || dis2.value.length > 0) {
dis1.disabled = true;
} else {
dis1.disabled = false;
}
};
There is a working example :
JSBin Example

Looking for something like this behaviour?
var last = "";
var dis1 = document.getElementById("aht-home-city");
dis1.onchange = function () {
last = "city";
document.getElementById("IDX-aw_zipcode").disabled = true;
}
var dis2 = document.getElementById("IDX-aw_zipcode");
dis2.onchange = function () {
last = "zipcode";
if (this.value != "" || this.value.length > 0) {
document.getElementById("aht-home-city").disabled = true;
}
}
Check this jsFiddle
Note: there was also a missing </select> tag in the HTML.

Related

Dropdown menu with user input text field and multiple selections

I'm looking to do a dropdown menu with user input, but I want the user to be able to add multiple options.
I was trying to do a datalist with this, but when it came time for multiple inputs then I read that datalist can only do that with email and files.
Here's an example of my current code:
HTML:
<input type="text" name="users" id="users" list="allowedUsers">
<datalist id="editUsers">
<option value="bob"></option>
</datalist>
JS:
$('#users').keypress(function(event){
var keyCode = (event.keyCode ? event.keyCode : event.which)
if(keyCode == '13') {
var inputVal = $(this).val();
$(#editUsers).append('<option value="'+inputVal+'">'+inputVal+'</option>')
}
});
The user can then click on a value and if they click on another either add that one in or when they do a comma then they can click to add. Not sure what would be easiest.
Thanks!
Chek this: https://selectize.github.io/selectize.js/
And in mid time maybe you could get away with something like this:
1 example:
It works by clicking the items, input is readonly...
$('#users').focus(function(){
$('#editUsers').show();
});
$('#editUsers').change(function() {
var val = $("#editUsers option:selected").text();
var inpoutVal = $('#users').val();
if (inpoutVal!=="") {
$('#users').val(inpoutVal+","+val)
}else{
$('#users').val(val)
}
});
#editUsers {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="users" id="users" readonly>
<select id="editUsers" multiple>
<option>Bob</option>
<option>Jhon</option>
<option>Yoda</option>
</select>
2nd example:
this is just something i trued to cook up, but it got out of hand, anyway try to pres some starting letter like B, or Y, then add cooma , . Anyway it does not definlty work as it should but maybe will someone get inspired by this failed attempt. ;)
Its late here cant work on it anymore...
$('#users').focus(function() {
$('#editUsers').show();
});
$("#users").bind('input', function() {
console.clear();
var inputVal = $("#users").val();
var inputVal2 = inputVal.split(",");
var last = inputVal2[inputVal2.length - 1];
$('#editUsers option').each(function() {
var selVal = $(this).val();
if (selVal.indexOf(last) > -1 && inputVal.indexOf(",") <= 0) {
$("#users").val(selVal + ",")
} else if (selVal.indexOf(last) > -1 && inputVal.indexOf(",") > -1) {
var newval = $("#users").val();
var newval2 = newval.split(",");
newval2.pop()
newval2
$("#users").val(newval2 + "," + selVal)
}
});
});
#editUsers {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="users" id="users">
<select id="editUsers" multiple>
<option>Bob</option>
<option>Jhon</option>
<option>Yoda</option>
</select>

inputs preventing submit form

so i'm working on a script that looks like this
<html>
CODE HTML WITH FORM ACTION POST
<script>
function chide() {
document.getElementById("ccin").style.display = 'none';
document.getElementById("naiss").style.display = 'none';
document.getElementById("account").style.display = 'none';
}
function ccheck(x) {
chide();
if(x == "variable1") {
document.getElementById("account").style.display = '';
document.getElementById("naiss").style.display = ''; }
if(x == "variable2") {
document.getElementById("account").style.display = '';
}
</script>
<div>
<td>
<tr><td width="560"><label> <font face="tahoma"> Your infos : </font></label></td>
<td width="">
<select style="width: 180px;" class="r_ddc_select" name="infos" onchange="ccheck(this.options[this.selectedIndex].value);" required="required">
<option value="">Select</option>
<option value="variable1">XXX</option>
<option value="variable1">YYY</option>
<option value="variable2">ZZZ</option>
<input type="text" name="bithdate" required="" >
<input type="text" name="account" required="" >
<input type="text" name="ccin" required="" >
the problem is that when an input is not showing like for example variable2 only shows the input account, i can't submit the form because apparently the other inputs are preventing it even if they're not showing on the page and i need all the inputs with the required option
The required attribute will always prevent the form from being submitted when the input is not filled no matter if visible or not as long as it's part of the DOM. As an easy fix I would suggest you to disable required with document.getElementById("account").required = false; when hiding it and enable it again when showing it.
EDIT: improved functions suggestion
function chide() {
document.getElementById("ccin").style.display = 'none';
document.getElementById("naiss").style.display = 'none';
document.getElementById("account").style.display = 'none';
document.getElementById("ccin").required = false;
document.getElementById("naiss").required = false;
document.getElementById("account").required = false;
}
function ccheck(x) {
chide();
if(x == "variable1") {
document.getElementById("account").style.display = '';
document.getElementById("naiss").style.display = '';
document.getElementById("account").required = true;
document.getElementById("naiss").required = true;
} else if(x == "variable2") {
document.getElementById("account").style.display = '';
document.getElementById("account").required = true;
}
}

Show loading gif onkeypress

So I have an input and dataList:
<div id="namearea">
<h2>City Name:</h2>
<div>
<input id="citiesinput" list="cities">
<datalist id="cities"></datalist>
<button id="search">
Search
</button>
<span class="loading" id="loadingnames">
<img src="/gif" alt="icon" />
Loading...
</span>
</div>
</div>
I have already used JS to fill the dataList with options.
What I want to do is display the loading gif from when i start typing in the input until I have chosen an option or pressed the search button
current JS:
var cityArray;
window.onload = function() {
processCities();
document.getElementById("search").onclick = findWeather;
document.getElementById("citiesinput").addEventListener("onkeypress", showLoad);
};
function showLoad () {
var input = document.getElementById("citiesinput").value;
if(input !== "" || cityArray.indexOf(input) == -1) {
document.getElementById("loadingnames").style.display = "block";
}
}
I have put a fiddle together for you here. I use the keyup event because the keypress event is called before the first key is registered in the input value.
input.addEventListener('keyup', function(){
loading.style.display = input.value.length ? 'block' : 'none';
});
You must also remember to remove the loader if the condition is not met.
Use opacity instead of display. Reason being when you set the display to inline-block, you will find your parent div "glitching" its height to adjust its content to the image div
Use keyup event after you press a key, it will trigger the function
var cityArray;
cityArray = ["city1", "city2"]
function findWeather() {
}
window.onload = function() {
//processCities();
//document.getElementById("search").onclick = findWeather;
document.getElementById("citiesinput").addEventListener("keyup", showLoad);
document.getElementById("search").addEventListener("click", showLoad);
};
function showLoad() {
var input = document.getElementById("citiesinput").value.trim();
if (input == "") {
document.getElementById("loadingnames").style.opacity = "0";
return
}
if (cityArray.indexOf(input) == -1) {
document.getElementById("loadingnames").style.opacity = "1";
} else {
document.getElementById("loadingnames").style.opacity = "0";
}
}
<div id="namearea">
<h2>City Name:</h2>
<div>
<input id="citiesinput" list="cities">
<datalist id="cities"></datalist>
<button id="search">
Search
</button>
<span class="loading" id="loadingnames" style="opacity:0;">
<img src="http://bestwallpaperhd.com/wp-content/uploads/2012/12/animated-wallpaper-gif.gif" alt="icon " id="city_img " style="width:50px;height:50px;"/>Loading...
</span>
</div>
</div>

How to get value from one form and post to the another form using javascript?

I am having two forms in same page,
Form 1 ID : home /
Form 2 ID : contact
I need the values filled in the form(home) in the text box of form2(contact) once the send button clicked.
<form id="home" method="get" action="#portfolio" role="form">
<select class="form-control" id="pd_howmuch">
<option>HOW MUCH ?</option>
<option>$100</option>
<option>$200</option>
</select>
<input id="pd_fname" type="text" name="name">
<input id="pd_lname" type="text" name="surname">
<input id="pd_zipcode" type="tel" name="zipcode">
<input id="pd_applynowbt" type="submit" value="Send">
</form>
<section id="portfolio">
<form id="contact" method="post" action="contact.php" role="form">
<select class="form-control" id="howmuch1">
<option>HOW MUCH ?</option>
<option>$100</option>
<option>$200</option>
</select>
<input id="fname1" type="text" name="name">
<input id="lname2" type="text" name="surname">
<input id="zipcode2" type="tel" name="zipcode">
<input id="applynowbt" type="submit" value="Submit">
</form>
</section>
Ok If I am understanding you correctly you wish to populate information from the first form to the second one.
So for this task to be accomplish you need to attach an event handler to the second form and prevent the default behavior
Working demo Hope to help you
var homeForm = document.getElementById("home");
var contactForm = document.getElementById("contact");
contactForm.addEventListener("submit", function(e) {
e.preventDefault();
contactForm.elements.item(0).value = homeForm.elements.item(0).value
contactForm.elements.item(1).value = homeForm.elements.item(1).value
contactForm.elements.item(2).value = homeForm.elements.item(2).value
contactForm.elements.item(3).value = homeForm.elements.item(3).value
}, false);
var sourceForm = document.getElementById("source-form");
var targetForm = document.getElementById("target-form");
function findTargetNode(nodeName, name) {
var targetElems = targetForm.elements;
for (var i = 0; i < targetElems.length; i++) {
var elem = targetElems.item(i);
if (elem.nodeName.toLowerCase() === nodeName && elem.name === name) {
return elem;
}
}
}
function setNodeValue(node, type, value) {
if (type === 'select')
{
for (var i = 0, options = node.options; i < options.length; i++) {
if (options[i].value === value) {
options[i].setAttribute('selected', 'true');
}
else {
options[i].removeAttribute('selected');
}
}
}
// else if (type === 'checkbox' || type === 'radio') { /* ... */ }
else {
node.value = value;
}
}
sourceForm.addEventListener("submit", function(e) {
for (var i = 0, elems = sourceForm.elements; i < elems.length; i++) {
var elem = elems.item(i);
if (!elem.name) {
continue;
}
var type = elem.nodeName.toLowerCase();
var targetNode = findTargetNode(type, elem.name);
if (!targetNode) {
continue;
}
setNodeValue(targetNode, type, elem.value);
}
e.preventDefault();
// targetForm.submit();
}, false);
<form id="source-form" action="javascript:void(0)" role="form">
<select class="form-control" id="my-select" name="my-select">
<option value="-1">HOW MUCH ?</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input id="my-text" type="text" name="my-text">
<input id="submit-source-form" type="submit" value="Fill the following form">
</form>
<section style="margin-top: 15px;">
<form id="target-form" method="post" action="contact.php" role="form">
<select class="form-control" id="my-select-2" name="my-select">
<option value="-1">HOW MUCH ?</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input id="my-text-2" type="text" name="my-text" value="this will change">
<input id="additional-value" type="text" name="additional" placeholder="this value will not change">
<input id="submit-target-form" type="submit" value="Send form">
</form>
</section>
https://jsfiddle.net/cremugnt/
Note: "Send form" action doesn't work here because of "Blocked form submission to 'http://stacksnippets.net/contact.php' because the form's frame is sandboxed and the 'allow-forms' permission is not set."
Note: This snippet can copy only "select" and "input" fields so if you want to work with other fields like "checkbox" or "radio" you get the idea.
This is a more global approach using OODK-JS and jQuery compatible with any types of field (note as field matching is based on the name attribute ):
$.noConflict();
OODK.config({
'path': {
'oodk': '../src',
'workspace': 'workspace'
}
});
OODK(function($, _){
// POO approach to solve this problem
// define a FormHelper class
var FormHelper = $.class(function($, µ, _){
$.protected('form');
$.public(function __initialize(form){
µ.form = form;
});
$.public(function exportToLiteral(){
var exprt = {};
jQuery(µ.form).find(":input, [textarea]").each(function(){
var val;
if(this.type === 'radio'){
val = µ.exportRadioField(this, exprt);
}else if(this.type === 'checkbox'){
val = µ.exportCheckboxField(this, exprt);
}else{
val = µ.exportField(this, exprt);
}
if(typeof val !== "undefined" &&
typeof jQuery(this).attr("name") !== "undefined"){
exprt[jQuery(this).attr("name")] = val;
}
});
return exprt;
});
// export argument html field fld to object literal exprt
$.protected(function exportField(fld, exprt){
return jQuery(fld).val();
});
// export argument checkbox html field fld to object literal exprt
$.protected(function exportCheckboxField(fld, exprt){
var val;
if(jQuery(fld).is(':checked')){
if(typeof exprt[jQuery(this).attr("name")] !== "undefined"){
val = exprt[jQuery(this).attr("name")];
}else{
val = [];
}
val.push(jQuery(this).val());
};
return val;
});
// export argument html radio field fld to object literal exprt
$.protected(function exportRadioField(fld, exprt){
var val;
if(jQuery(fld).is(':checked')){
val = jQuery(this).val();
}
return val;
});
// copy all values of the source form to the destination form passed
// as argument
$.public(function copyToForm(destForm){
var oSrcForm = this.exportToLiteral();
jQuery(destForm).find(":input, [textarea]").each(function(){
if(typeof oSrcForm[jQuery(this).attr("name")] !== "undefined"){
var srcVal = oSrcForm[jQuery(this).attr("name")];
if(this.type == 'checkbox'){
µ.copyToCheckboxField(this, srcVal, oSrcForm);
}else if(this.type == 'radio'){
µ.copyToRadioField(this, srcVal, oSrcForm);
}else{
µ.copyToField(this, srcVal, oSrcForm);
}
}
});
});
$.protected(function copyToField(fld, val, exprt){
jQuery(fld).val(val);
});
$.protected(function copyToCheckboxField(fld, val, exprt){
if(Array.isArray(srcVal) && srcVal.indexOf(jQuery(fld).val()) !== -1){
jQuery(fld).prop('checked', true);
}
});
$.protected(function copyToRadioField(fld, val, exprt){
if(exprt[jQuery(fld).attr("name")] == jQuery(fld).val()){
jQuery(fld).prop('checked', true);
}
});
});
jQuery(document).ready(function(){
jQuery('#pd_applynowbt').bind('click', function(evt){
// prevent the source form to be submitted
evt.preventDefault();
var formHelper = $.new(FormHelper, jQuery('#home'));
// copy all fields from form #home to form #contact
formHelper.copyToForm(jQuery('#contact'));
});
});
});

Trying to trigger clicks on product options at document.ready with jQuery in Bigcommerce Classic Next theme

OK, so I have a product landing page with no options to load specific product options, which creates a big problem when linking ecommerce sites with a product feed for specific sizes and their respective prices, weights, etc. So I have this landing page for a certain product, and I need to load the specific options on document.ready based on URI params. I want to pass "size" and trigger a click on Twin, Full, Queen, or King based on the query string. Here's an example of what I'm looking at: mattress product page. I'm not anywhere near to parsing and handling the parameters, though.
My problem is I jumped into HTML, CSS, Javascript, and jQuery all at once, and I'm not 100% as to what I'm doing with this. Right now I'm just trying to determine on which object I should be triggering the click. All of the tutorials I've found have a name to reference, as in this example jQuery not triggering on radio button change. I've tried a bunch of combinations of the attempts below in chrome's developer console, but it doesn't seem to include the jQuery scripts referenced in the header.
If someone could explain to be which class or selector would be the object I should be working with, how it's manipulated in the script, and how it would appear in the DOM, I would really appreciate it. Also, if anyone has any reference books to recommend, please do so.
Should it be something like
$(".ProductOptionList option:first").click();
or
$(".VariationSelect:eq(*index of array of selections I want to click*)").something? attr()? var()? html()?
Here are the (hopefully) relevant sections of javascript
from product.js:
$(document).ready(function() {
...
// disable all but the first variation box
$(".VariationSelect:gt(0)").attr('disabled', 'disabled');
var prodVarSelectionMap = {}
$(".VariationSelect").change(function() {
// cache a map of currently selected values.
var mapIndex = 0;
$('.VariationSelect').each(function() {
prodVarSelectionMap[mapIndex] = this.value;
mapIndex++;
});
// get the index of this select
var index = $('.VariationSelect').index($(this));
// deselected an option, disable all select's greater than this
if (this.selectedIndex == 0) {
$('.VariationSelect:gt(' + index + ')').attr('disabled', 'disabled')
updateSelectedVariation($('body'));
return;
}
else {
// disable selects greater than the next
$('.VariationSelect:gt(' + (index + 1) + ')').attr('disabled', 'disabled')
}
//serialize the options of the variation selects
var optionIds = '';
$('.VariationSelect:lt(' + (index + 1) + ')').each(function() {
if (optionIds != '') {
optionIds += ',';
}
optionIds += $(this).val();
});
// request values for this option
$.getJSON(
'/remote.php?w=GetVariationOptions&productId=' + productId + '&options=' + optionIds,
function(data) {
// were options returned?
if (data.hasOptions) {
// load options into the next select, disable and focus it
$('.VariationSelect:eq(' + (index + 1) + ') option:gt(0)').remove();
$('.VariationSelect:eq(' + (index + 1) + ')').append(data.options).attr('disabled', false).focus();
// auto select previously selected option, and cascade down, if possible
var preVal = prodVarSelectionMap[(index + 1)];
if (preVal != '') {
var preOption = $('.VariationSelect:eq(' + (index + 1) + ') option[value=' +preVal+']');
if (preOption) {
preOption.attr('selected', true);
$('.VariationSelect:eq(' + (index + 1) + ')').trigger('change');
}
}
}
else if (data.comboFound) { // was a combination found instead?
// display price, image etc
updateSelectedVariation($('body'), data, data.combinationid);
}
}
);
});
//radio button variations
$('.ProductOptionList input[type=radio]').click(function() {
//current selected option id
var optionId = $(this).val();
// request values for this option
$.getJSON(
'/remote.php?w=GetVariationOptions&productId=' + productId + '&options=' + optionId,
function(data) {
if (!data) {
return;
}
if (data.comboFound) { // was a combination found instead?
// display price, image etc
updateSelectedVariation($('body'), data, data.combinationid);
}
}
);
});
from product.functions.js:
/* Product Variations */
var baseProduct = {};
function updateSelectedVariation(parent, variation, id) {
if(typeof(parent) == 'undefined') {
parent = $('body');
}
else {
parent = $(parent);
}
if (typeof id == 'undefined') {
id = '';
}
if(typeof(baseProduct.price) == 'undefined') {
if($('.AddCartButton', parent).css('display') == "none") {
var cartVisible = false;
}
else {
var cartVisible = true;
}
var stockMessageVisible = false;
if($('.OutOfStockMessage', parent).css('display') != 'none') {
stockMessageVisible = true;
}
var price;
$('.VariationProductPrice', parent).each(function(){
var $$ = $(this);
if ($$.is('input')) {
price = $$.val();
} else {
price = $$.html();
}
});
baseProduct = {
saveAmount: $.trim($('.YouSaveAmount', parent).html()),
price: $.trim(price),
sku: $.trim($('.VariationProductSKU', parent).html()),
weight: $.trim($('.VariationProductWeight', parent).html()),
thumb: $.trim($('.ProductThumbImage img', parent).attr('src')),
cartButton: cartVisible,
stockMessage: stockMessageVisible,
stockMessageText: $('.OutOfStockMessage', parent).html()
};
}
// Show the defaults again
if(typeof(variation) == 'undefined') {
$('.WishListVariationId', parent).val('');
$('.CartVariationId', parent).val('');
if(baseProduct.saveAmount) {
$('.YouSave', parent).show();
$('.YouSaveAmount').html(baseProduct.saveAmount);
} else {
$('.YouSave', parent).hide();
}
$('.VariationProductPrice', parent).each(function(){
var $$ = $(this);
if ($$.is('input')) {
$$.val(baseProduct.price);
} else {
$$.html(baseProduct.price);
}
});
$('.VariationProductSKU', parent).html(baseProduct.sku);
$('.VariationProductWeight', parent).html(baseProduct.weight);
$('.ProductThumbImage img', parent).attr('src', baseProduct.thumb);
$(parent).attr('currentVariation', '');
$(parent).attr('currentVariationImage', '')
if(baseProduct.sku == '') {
$('.ProductSKU', parent).hide();
}
if(baseProduct.cartButton) {
$('.AddCartButton', parent).show();
if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
$('.QuantityInput', parent).show();
}
}
if(baseProduct.stockMessage) {
$('.OutOfStockMessage', parent)
.show()
.html(baseProduct.stockMessageText)
;
}
else {
$('.OutOfStockMessage').hide();
}
$('.InventoryLevel', parent).hide();
}
// Otherwise, showing a specific variation
else {
$('.WishListVariationId', parent).val(id);
$('.CartVariationId', parent).val(id);
$('.VariationProductPrice', parent).each(function(){
var $$ = $(this),
price = baseProduct.price;
price = '777';
if (variation.price !== undefined) {
price = variation.price;
}
if ($$.is('input')) {
$$.val(price.replace(/[^0-9\.,]/g, ''));
} else {
$$.html(price);
}
});
if(variation.sku != '') {
$('.VariationProductSKU', parent).html(variation.sku);
$('.ProductSKU', parent).show();
}
else {
$('.VariationProductSKU', parent).html(baseProduct.sku);
if(baseProduct.sku) {
$('.ProductSKU', parent).show();
}
else {
$('.ProductSKU', parent).hide();
}
}
$('.VariationProductWeight', parent).html(variation.weight);
if(variation.instock == true) {
$('.AddCartButton', parent).show();
if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
$('.QuantityInput', parent).show();
}
$('.OutOfStockMessage', parent).hide();
}
else {
$('.AddCartButton, .QuantityInput', parent).hide();
$('.OutOfStockMessage', parent).html(lang.VariationSoldOutMessage);
$('.OutOfStockMessage', parent).show();
}
if(variation.thumb != '') {
ShowVariationThumb = true;
$('.ProductThumbImage img', parent).attr('src', variation.thumb);
$(parent).attr('currentVariation', id);
$(parent).attr('currentVariationImage', variation.image);
$('.ProductThumbImage a').attr("href", variation.image);
}
else {
$('.ProductThumbImage img', parent).attr('src', baseProduct.thumb);
$(parent).attr('currentVariation', '');
$(parent).attr('currentVariationImage', '')
}
if(variation.stock && parseInt(variation.stock)) {
$('.InventoryLevel', parent).show();
$('.VariationProductInventory', parent).html(variation.stock);
}
else {
$('.InventoryLevel', parent).hide();
}
if(variation.saveAmount) {
$('.YouSave', parent).show();
$('.YouSaveAmount').html(variation.saveAmount);
$('.RetailPrice').show();
} else {
$('.YouSave', parent).hide();
$('.RetailPrice').hide();
}
}
}
function GenerateProductTabs()
{
var ActiveTab = 'Active';
var ProductTab = '';
var TabNames = new Array();
TabNames['ProductDescription'] = lang.Description;
TabNames['ProductWarranty'] = lang.Warranty;
TabNames['ProductOtherDetails'] = lang.OtherDetails;
TabNames['SimilarProductsByTag'] = lang.ProductTags;
TabNames['ProductByCategory'] = lang.SimilarProducts;
TabNames['ProductReviews'] = lang.Reviews;
TabNames['ProductVideos'] = lang.ProductVideos;
TabNames['SimilarProductsByCustomerViews'] = lang.SimilarProductsByCustomerViews;
$('.Content .Moveable').each (function() {
if (this.id == 'ProductBreadcrumb' ||
this.id == 'ProductDetails' ||
$(this).html() == '' ||
!TabNames[this.id]
) {
return;
}
TabName = TabNames[this.id];
ProductTab += '<li id="'+this.id+'_Tab" class="'+ActiveTab+'"><a onclick="ActiveProductTab(\''+this.id+'_Tab\'); return false;" href="#">'+TabName+'</a></li>';
if (ActiveTab == '')
{
$('#'+this.id).hide();
}
$('#'+this.id).removeClass('Moveable');
ActiveTab = "";
});
if (ProductTab != '')
{
$('#ProductTabsList').html(ProductTab);
}
}
this is from the dev console:
<div class="productAttributeList" style="">
<div class="productAttributeRow productAttributeConfigurablePickListSet productAttributeRuleCondition" id="a02034dba575c64f27ad8724b46b9d4d">
<div class="productAttributeLabel">
<label for="93a2b37dabd1fe9deae210d2ac0a6b80">
<span class="required">*</span>
<span class="name">
Mattress Size: </span>
</label>
</div>
<div class="productAttributeValue">
<div class="productOptionViewRectangle">
<ul class="list-horizontal">
<li class="option selectedValue">
<label for="a224072f64cc4ad05f0cabb0ec516c7d">
<input type="radio" class="validation" name="attribute[251]" value="2" id="a224072f64cc4ad05f0cabb0ec516c7d">
<span class="name">TwinXL</span>
</label>
</li>
<li class="option">
<label for="b0204680fe57cec48dab9edc28a34a7d">
<input type="radio" class="validation" name="attribute[251]" value="3" id="b0204680fe57cec48dab9edc28a34a7d">
<span class="name">Full</span>
</label>
</li>
<li class="option">
<label for="83f68b784f33ebf11dbde126b9a9fc97">
<input type="radio" class="validation" name="attribute[251]" value="4" id="83f68b784f33ebf11dbde126b9a9fc97">
<span class="name">Queen</span>
</label>
</li>
<li class="option">
<label for="fe4651efe956ed8fb3f9b0635e35322d">
<input type="radio" class="validation" name="attribute[251]" value="5" id="fe4651efe956ed8fb3f9b0635e35322d">
<span class="name">King</span>
</label>
</li>
<li class="option">
<label for="c6c1071e4bc6a5edfd0524dd8ad042c2">
<input type="radio" class="validation" name="attribute[251]" value="6" id="c6c1071e4bc6a5edfd0524dd8ad042c2">
<span class="name">California King</span>
</label>
</li>
</ul>
</div>
</div>
<div class="cf"></div>
</div>
<div class="productAttributeRow productAttributeConfigurablePickListSet productAttributeRuleCondition" id="668978c662c62cf05439063491e89dc9">
<div class="productAttributeLabel">
<label for="e58baa61c3f97085e9c2e7742dbf1595">
<span class="required">*</span>
<span class="name">
Add Box Spring Foundation: </span>
</label>
</div>
<div class="productAttributeValue">
<div class="productOptionViewSelect">
<div class="selector fixedWidth" id="uniform-e58baa61c3f97085e9c2e7742dbf1595"><span style="-webkit-user-select: none;">Mattress Only</span><select class="validation" id="e58baa61c3f97085e9c2e7742dbf1595" name="attribute[1123]">
<option value="">
-- Please Choose an Option -- </option>
<option value="36" selected="selected">Mattress Only</option>
<option value="37">Standard Height (9")</option>
<option value="38">Low Profile (5")</option>
</select></div>
</div> </div>
<div class="cf"></div>
</div>
<div class="productAttributeRow productAttributeConfigurablePickListSet" id="11d522cf8329ffc8cb74e3c2934a9a3d">
<div class="productAttributeLabel">
<label for="fbde0c153d55c827e931b260145f3442">
<span class="name">
Add Premium Bed Frame: </span>
</label>
</div>
<div class="productAttributeValue">
<div class="productOptionViewSelect">
<div class="selector fixedWidth" id="uniform-fbde0c153d55c827e931b260145f3442"><span style="-webkit-user-select: none;">
-- None --
</span><select class="validation" id="fbde0c153d55c827e931b260145f3442" name="attribute[1136]">
<option value="" selected="selected">
-- None --
</option>
<option value="35">Add Bed Frame</option>
</select></div>
</div> </div>
<div class="cf"></div>
</div>
<div class="productAttributeRow productAttributeConfigurablePickListSet" id="d8e2352c51c3bff1643b103c8e92f5bd">
<div class="productAttributeLabel">
<label for="96ce2d73c8b6a02a747111a1b793442c">
<span class="name">
Add Premium Mattress Protector: </span>
</label>
</div>
<div class="productAttributeValue">
<div class="productOptionViewSelect">
<div class="selector fixedWidth" id="uniform-96ce2d73c8b6a02a747111a1b793442c"><span style="-webkit-user-select: none;">
-- None --
</span><select class="validation" id="96ce2d73c8b6a02a747111a1b793442c" name="attribute[1149]">
<option value="" selected="selected">
-- None --
</option>
<option value="34">Add Mattress Protector</option>
</select></div>
</div> </div
If you're working with radios and attempting to deselect all and then select a specific one you need two things: name and a unique identifier. Use the name to deselect all the ones in that group, and use the ID to select the one you need. If you don't have ID, you could always use value. Or, if you just want to select the first one available, use the name to get the radio/check group, and use the .first() filter to get the first matched element.
Info on selectors: http://api.jquery.com/category/selectors/
How to use the attribute selector for the name or value: http://api.jquery.com/attribute-equals-selector/
How to get via ID: http://api.jquery.com/id-selector/
Triggering a "click" event will also trigger any events bound to click or change on an element. If you need that, then trigger the click like you're trying. If you just need to toggle the check state, though, you can use this method: How to uncheck a radio button?
As an edit after your comment:
It's nice to see you using some core JavaScript for this. When I work with forms, I like to use a combination with jQuery. Something like:
$('[name="attribute[251]"]').each(function() {
this.checked = false;
});
or
$('#b0204680fe57cec48dab9edc28a34a7d')[0].checked = true;
Everyone has their own preference on this. This is just an example approach.
Default Select first variation:
Add this in Product.html ( Bigcommerce Theme file )
For Size:
$(document).ready(function() {
$(".productOptionViewRectangle ul").each(function() {
$(this).children("li").first().addClass("selectedValue");
$("li.selectedValue input.validation").attr('checked',true);
});
});
For Color Swatch:
$(document).ready(function() {
$(".productOptionPickListSwatch ul").each(function() {
$(this).children("li").first().addClass("selectedValue");
$("li.selectedValue input.validation").attr('checked',true);
});
});

Categories

Resources