If form multiple selects value are euals zero - javascript

I have multiple forms with one, two, three html select. I just want simple code if form select selected value equals to zero then console.log "please select order". Following is the script which I am working on.
$('form').submit(function(event){
event.preventDefault();
var dataitem = $(this).attr('data-item');
if (dataitem == 1) {
console.log(dataitem);
var $myform = $(this),
flavour1 = $myform.find( "select[name='flavour1']" ).val(),
drink = $myform.find( "select[name='drink']" ).val();
console.log("Flavour :" + flavour1 + ", Drink :" + drink);
} else if (dataitem == 2) {
console.log(dataitem);
var $myform = $(this),
flavour1 = $myform.find( "select[name='flavour1']" ).val(),
flavour2 = $myform.find( "select[name='flavour2']" ).val(),
drink = $myform.find( "select[name='drink']" ).val();
console.log("Flavour1 :" + flavour1 + ", Flavour2 :" + flavour2 + ", Drink :" + drink);
} else {
console.log(dataitem);
var $myform = $(this),
flavour1 = $myform.find( "select[name='flavour1']" ).val(),
flavour2 = $myform.find( "select[name='flavour2']" ).val(),
flavour3 = $myform.find( "select[name='flavour3']" ).val(),
drink = $myform.find( "select[name='drink']" ).val();
console.log("Flavour1 :" + flavour1 + ", Flavour2 :" + flavour2 + ", Flavour3 :" + flavour3 + ", Drink :" + drink);
}
});
please advice as i am stuck at this point of selection. If each select value == 0.
Thanks

Usualy if you have multiple components similar you can use:
$myform.find("select")
This will give you all "select" elements in your form. And then you can find the value one by one using:
$myform.find("select").each(function(index, value){
var valSelec = $(this).val();
///Make your if
})

I create a function: validateSelect() that search on all selects of form and verify if the option selected was empty, if true they return false.
Example:
$("form").submit(function(e) {
e.preventDefault();
if (validateSelect()) {
console.log('All are filled valid');
} else {
console.log('Invalid');
}
});
function validateSelect() {
var fleg = true;
$.each($('select option:selected'), function(key, val) {
if (val.value.length < 1) {
fleg = false;
}
});
return fleg;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form>
<select name="number">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="letter">
<option value=""></option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<input type="submit">
</form>

Related

Take a value text not id value in dropdown list

I have a dropdownlist
<option value="13">MATT</option>
<option value="15">MeT</option>
I would like to take the text instead id value from a dropdownlist:
what's wrong with this line??
if ($("select[title='" + tipologiaSelector + '"] ("option: selected")').text() == "MATT")
thank you
You can get value of option by text by spread operator and find as
var res = [...document.getElementsByTagName("option")].find(c=>c.innerText == "MATT").value;
If you want to use jquery, use each function as
$("#test option").each(function(index, item){
if( $(item).text() == "MATT") {
id = $(item).attr("value");
return;
}
})
var res = [...document.getElementsByTagName("option")].find(c=>c.innerText == "MATT").value;
console.log(res)
var id;
$("#test option").each(function(index, item){
if( $(item).text() == "MATT") {
id = $(item).attr("value");
return;
}
})
console.log(id)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test">
<option value="13">MATT</option>
<option value="15">MeT</option>
</select>
Your selector has the wrong syntax. unmatched quotes: title='" and spacing after : and no need for paranthesis and quotes around the option:selected.
tipologiaSelector = "mytitle";
if ($("select[title=\"" + tipologiaSelector + '"] option:selected').text() == "MATT") console.log("== MATT");
$('select').change( function(){
if ($("select[title=\"" + tipologiaSelector + '"] option:selected').text() == "MATT") console.log("== MATT");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select title="mytitle">
<option value="13">MATT</option>
<option value="15">MeT</option>
</select>

How to update the div text based on dropdown value?

I have 4 dropdowns, 2 for the "From" destination and 2 for the "To" destination.
What I want to do is to update the #from div and the #to div based on the dropdown values.
For example on the "From" destination, if 1 and 5 is selected then the #from must show 1 -> 5
That means that while selecting the 1, it will show 1 -> until the user selects from the 2nd dropdown and it completes the sequence.
from
<select id="from_country">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="from_city">
<option value="1">4</option>
<option value="2">5</option>
<option value="3">6</option>
</select>
<br>
<br />
to
<select id="to_country">
<option value="1">7</option>
<option value="2">8</option>
<option value="3">9</option>
</select>
<select id="to_city">
<option value="1">10</option>
<option value="2">11</option>
<option value="3">12</option>
</select>
<div id="from"></div>
<div id="to"></div>
$('#from_country').change(function () {
var country = $('option:selected', this).val();
var city = $('#from_city').val();
$('#from').text(country + "->" + city);
})
$('#from_city').change(function () {
var city = $('option:selected', this).val();
var country = $('#from_country').val();
$('#from').text(country + "->" + city);
})
$('#to_country').change(function () {
var country = $('option:selected', this).val();
var city = $('#to_city').val();
console.log(country + "->" + city)
$('#to').text(country + "->" + city);
})
$('#to_city').change(function () {
var city = $('option:selected', this).val();
var country = $('#to_country').val();
$('#to').text(country + "->" + city);
})
Try this
demo
Here is a simple solution: http://jsbin.com/huvilegeso/edit?html,js,output. I only did it for the From section. The To section is very similar.
var from = [null, '->'];
$('#from_country').on('change', function() {
from[0] = $(this).val();
renderFrom(from);
});
$('#from_city').on('change', function() {
from[2] = $(this).val();
renderFrom(from);
});
function renderFrom(from) {
$('#from').html(from.join(' '));
}
You can do something like this.
$('#from_country').change(function () {
$('#from').text( $('#from_country :selected').text() + '->' +
$('#from_city :selected').text());
});
$('#from_city').change(function () {
$('#from').text( $('#from_country :selected').text() + '->' +
$('#from_city :selected').text());
});
$('#to_country').change(function () {
$('#to').text( $('#to_country :selected').text() + '->' +
$('#to_city :selected').text());
});
$('#to_city').change(function () {
$('#to').text( $('#to_country :selected').text() + '->' +
$('#to_city :selected').text());
});

JQuery autocomplete works for one section but not the other

I'm trying to get a JQuery function to pick up specific changes to a form and then plug the information into equations so that each section of the form has answers created for it automatically. I got the first part of it to work (Quantity for Posts) but can't get the second part to work (Quantity for Rails). If anyone can point out or explain where I went wrong and how I could fix it it would be greatly appreciated! Thanks!
Here is a JSFiddle - http://jsfiddle.net/gv0029/ncn42/1/
HTML:
<fieldset id="fence">
<div name="inputFence" class="inputFence">
<legend><strong>Fence Description</strong>
</legend>
<label>Footage:
<input name="footage_1" class="footage" />
</label>
<select name="fenceHeight_1" class="fenceHeight">
<option value="select">Select Fence Height</option>
<option value="6" id="fH6">6 Ft.</option>
<option value="8" id="fH8">8 Ft.</option>
</select>
<legend><strong>Post Type</strong>
</legend>
<label>Post Quantity:
<input name="postQuantity_1" class="postQuantity" />
</label>
<legend><strong>Rail Type</strong>
</legend>
<select name="6foc_1" class="6foc">
<option value="select">6 Ft. on Center?</option>
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
<label>Quantity:
<input class="railQuantity" name="railQuantity_1" />
</label>
</fieldset>
<div>
<input type="button" id="btnAddFence" value="Add Another Fence" />
<input type="button" id="btnDelFence" value="Remove Fence" />
</div>
</form>
JS:
//Quantity for Posts
$(document.body).on('keypress keydown keyup change', '[class^="footage"] ', function () {
var footage = parseFloat($(this).val(), 10);
var total = '';
var parts = $(this).attr('name').split("_");
var fenceNumber = parts[1];
if (!isNaN(footage)) {
total = Math.ceil(footage / 7);
$(":input[name='postQuantity_" + fenceNumber + "'" + ']').val(total.toString());
} else {
$(":input[name='postQuantity_" + fenceNumber + "'" + ']').val("");
}
});
//Quantity for Rails
$(document.body).on('keypress keydown keyup change', '[class^="footage"] [class^="fenceHeight"] [class^="6foc"]', function () {
var parts = $(this).attr('name').split("_");
var fenceNumber = parts[1];
var footage = parseFloat($(":input[name='footage_" + fenceNumber + "'" + ']').val(), 10);
var fenceHeight = $(":input[name='fenceHeight_" + fenceNumber + "'" + ']').val();
var railQuantity = $(":input[name='railQuantity_" + fenceNumber + "'" + ']').val();
var total = '';
var sfoc = $(":input[name='6foc_" + fenceNumber + "'" + ']').val();
if (fenceHeight = !NaN) {
if (sfoc == "no") {
if (fenceHeight == '8') {
total = (Math.ceil(footage / 8) * 4);
}
if (fenceHeight == '6') {
total = (Math.ceil(footage / 8) * 3);
}
railQuantity.val(total);
}
if (sfoc == "yes") {
if (fenceHeight == '8') {
total = (Math.ceil(footage / 12) * 4);
railQuantity.val(total);
}
if (fenceHeight == '6') {
alert("Error: 6ft on Center cannot use 6ft posts");
railQuantity.val("ERROR");
}
}
} else {
railQuantity.val("");
}
});
//Dynamic Fence Input Fields
$('#btnAddFence').click(function () {
// create the new element via clone()
var newElem = $('.inputFence:last').clone();
// insert the new element after the last "duplicable" input field
$('.inputFence:last').after(newElem);
// enable the "remove" button
$('#btnDelFence').removeAttr('disabled');
//get the input name and split into array (assuming your clone is always last)
var parts = $('.fenceHeight:last').attr('name').split("_");
//change the second element of the array to be one higher
parts[1]++;
//join back into a string and apply to the new element
$('.fenceHeight:last').attr('name', parts.join("_"));
//do the same for other two inputs
parts = $('.postQuantity:last').attr('name').split("_");
parts[1]++;
$('.postQuantity:last').attr('name', parts.join("_"));
parts = $('.footage:last').attr('name').split("_");
parts[1]++;
$('.footage:last').attr('name', parts.join("_"));
parts = $('.6foc:last').attr('name').split("_");
parts[1]++;
$('.6foc:last').attr('name', parts.join("_"));
});
$('#btnDelFence').click(function () {
//remove the last inputFence
$('.inputFence:last').remove();
// if only one element remains, disable the "remove" button
if ($('.inputFence').length == 1) $('#btnDelFence').attr('disabled', 'disabled');
});
$('#btnDelFence').attr('disabled', 'disabled');
You had a few problems.
First was this line:
$(document.body).on('keypress keydown keyup change', '[class^="footage"] [class^="fenceHeight"] [class^="6foc"]',
You have to separate the different inputs with a comma as shown here:
$(document.body).on('keypress keydown keyup change', '[class^="footage"],[class^="fenceHeight"],[class^="6foc"]',
Second was this line:
var fenceHeight = $(":input[name='fenceHeight_" + fenceNumber + "'" + ']').val();
You're getting the value of the select, when really you want the value of the selected option:
var fenceHeight = $(":input[name='fenceHeight_" + fenceNumber + "'" + ']').find('option:selected').val();
Third was this line:
var railQuantity = $(":input[name='railQuantity_" + fenceNumber + "'" + ']').val();
You're getting the value of this line, when down in the code you're actually trying to set the value of the value. What you want is just the element. I've left the quantity in there in case you want that later, but repurposed railQuantity:
var railQuantity = $(":input[name='railQuantity_" + fenceNumber + "'" + ']');
var railQuantityval = $(":input[name='railQuantity_" + fenceNumber + "'" + ']').val();
Fourth is your if statement:
if (fenceHeight = !NaN) {
You can't really use it like that. Use this instead:
if (!isNaN(Number(fenceHeight))) {
Down in the if statement, you also could benefit from if/else statements instead of just if statements. I've changed those to reflect this.
You were also missing the railsQuantity element in your add function, which I added for you:
parts = $('.railQuantity:last').attr('name').split("_");
parts[1]++;
$('.railQuantity:last').attr('name', parts.join("_"));
Updated fiddle here.

jQuery select option value

How do you set the "city" value to the same thing as country value when there is no option for a city?
For example, Benin doesn't have an option to select a city inside of it. At this link http://jsfiddle.net/yPb6N/1/, if you select "Benin", underneath the dropdown it displays Benin undefined. How do you make it display Benin Benin?
<select id="country-select">
<option value="us">US</option>
<option value="germany">Germany</option>
<option>Ireland</option>
<option>Benin</option>
<option>Italy</option>
</select>
<select id="us-select" class="sub-menu hide">
<option value="austin">Austin</option>
</select>
<select id="germany-select" class="sub-menu hide">
<option value="berlin">Berlin</option>
</select>
<p></p>
<font size="5"><font color="red"><div class="countryvalue" >Value</div></font></font> <br/>
​
function countrySelectChanged() {
$('.sub-menu').hide();
var selectedCountry = $('#country-select').val();
if (selectedCountry) {
$('#' + selectedCountry + '-select').show();
}
}
$(document).ready(function() {
$('#country-select').change(countrySelectChanged );
countrySelectChanged();
$("#country-select").change(function () {
var str = $('#country-select').val() + " " + $("#" + $("#country-select option:selected").val() + "-select option:selected").val();
$("#country-select option:selected").each(function () {
});
$(".countryvalue").text(str);
})
.change();
});
​
.hide {
display: none;
}​
My code is not working
if (($('#country-select').val() != "us") || ($('#country-select').val() != "germany")) {
$("#" + $("#country-select option:selected").val() + "-select option:selected").val() == $('#country-select').val();
}
thanks :-)
This line:
var str = $('#country-select').val() + " " + $("#" + $("#country-select option:selected").val() + "-select option:selected").val();
Needs to be somthing like:
var country = $('#country-select option:selected').val();
var city = $("#" + country + "-select option:selected").val() || country;
$(".countryvalue").text(country + " " +city);
This way, if the name of the city doesn't exist, it will use the name of the country. Also, it doesn't perform multiple selectors for the same element, which is wasteful.
Here is the updated fiddle.
I guess that you want to print only the country name if there is no city associated with this country. If so, I have created this fiddle : http://jsfiddle.net/scaillerie/tSgVL/1/ .
In fact, you have to test if the list associated with your country exists or not :
hasCity = $("#" + $("#country-select option:selected").val() + "-select").length !== 0
and then print or not the country.
Edit
It seems that you want to duplicate the country, so depending of the previous test, you will have :
str = $country.val() + " " + (hasCity ? $("#" + country_val + "-select option:selected").val() : $country.val());
basically what #Aesthete said, i just refactored the whole function (took some minutes), maybe you like it (i updated the fiddle: http://jsfiddle.net/yPb6N/4/):
$(document).ready(function() {
var country
, city
, $selected
, $cs = $('#country-select')
, $cv = $(".countryvalue");
$cs.on('change', function() {
country = $cs.val() || $cs.text();
$selected = $cs.find(':selected');
city = $selected.val() || $selected.text();
$('.sub-menu').addClass('hide');
if($selected.val()) {
$('#' + $selected.val() + '-select').removeClass('hide');
city = $('#' + $selected.val() + '-select').val() || country;
}
$cv.text(country + ' ' + city);
});
$cs.trigger('change');
});​

Browser back-button when a list of values selection

I'm trying to keep the list of values from drop-down selections when the browser back-button is click after the form has been submitted. I tried using Ben Alman's bbq jquery, but failed to get things working. Here's what I've been trying. Please help.
Many thanks in advance.
HTML
<form action="something.py" id="formName">
<table id = "tabName">
<tr>
<th>Name</th><th>Number</th>
</tr>
<tr>
<td>
<select id="myname" name="myname">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</td>
<td>
<select id="mynumber" name="mynumber">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
</tr>
</table>
<input type="submit" value="submit" />
</form>
JQuery:
var selected_value = [];
$('#mynumber').change(function() {
var name = $('#myname').val();
var number = $('#mynumber').val();
$("#tabName tr:last").before("<tr><td>" + name + "</td><td>" + number + "</td></tr>");
selected_value.push(name);
});
$('#formName').submit(function() {
$.bbq.pushState({
values: selected_value
});
//return false;
});
$(window).bind("hashchange", function(e) {
var values = $.bbq.getState("url");
if (selected_value === values) {
$(this).addClass("current");
} else {
$(this).removeClass("current");
}
});
My solution (without cookies or localStorage) based on location.hash:
function addRow(name, number){
$("#tabName tr:last").before("<tr><td>" + name + "</td><td>" + number + "</td></tr>");
}
$(function(){
if(location.hash){
var rows = location.hash.substr(1).split(';');
for(var i = 0; i < rows.length; i++){
var row = rows[i].split(',');
if(row.length == 2){
addRow(row[0], row[1]);
}
}
}
$('#mynumber').change(function() {
var name = $('#myname').val();
var number = $('#mynumber').val();
location.hash = location.hash + (location.hash ? ';' : '') + name + ',' + number;
addRow(name, number);
});
});
I think it does what you have asked for - if not, please give me some feedback in comments.
$('#formName').submit(function() {
$.bbq.pushState({
values: selected_value
});
//return false;
});
should be
$('#formName').submit(function() {
$.bbq.pushState({
values: selected_value
});
//return false;
});
and
var values = $.bbq.getState("url");
should be
var values = $.bbq.getState("values");

Categories