JavaScript/jQuery: Validate Checkbox & Dropdown Pairing - javascript

I'm teaching myself JavaScript/jQuery. I have three pairs of checkboxes and dropdowns I want to validate:
code screencap
I want to validate that both parts of a pair are selected:
-- If a checkbox is checked, a value is also selected from the associated dropdown
-- Or, if a value is selected from a dropdown, the associated checkbox must be checked
I don't want to enable/disable the checkbox or dropdown during the process. I want to allow the user to check/select what they will, then check to see if both parts of a given pair are checked and selected on submit.
JSFiddle for the HTML: https://jsfiddle.net/6y6e0aod/5/
I spent a few hours on SO and googling in general, but couldn't find an example quite like this. Thanks ahead of time for any help.
<div>
<input type="checkbox">Vehicle 1
<select>
<option>Car</option>
<option>Truck</option>
<option>Van</option>
<option>Motorcycle</option>
</select>
</div>
<div>
<input type="checkbox">Vehicle 2
<select>
<option>Car</option>
<option>Truck</option>
<option>Van</option>
<option>Motorcycle</option>
</select>
</div>
<div>
<input type="checkbox">Vehicle 3
<select>
<option>Car</option>
<option>Truck</option>
<option>Van</option>
<option>Motorcycle</option>
</select>
</div>
<br /><br />
<button>submit data</button>

You can add a empty option to the select so that we can force the user to select one, then in the click handler of the button we can see whether if there is any checked checkbox where the select is empty like
$('#submit').click(function(e) {
var $invalid = $('input:checkbox:checked + select:has([value=""]:selected)');
if ($invalid.length) {
e.preventDefault();
alert('Need to select a value for: ' + $invalid.map(function() {
return this.previousSibling.nodeValue.trim();
}).get().join(', '));
return;
}
//it is valid so do your stuff here
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox">Vehicle 1
<select>
<option value=""></option>
<option>Car</option>
<option>Truck</option>
<option>Van</option>
<option>Motorcycle</option>
</select>
</div>
<div>
<input type="checkbox">Vehicle 2
<select>
<option value=""></option>
<option>Car</option>
<option>Truck</option>
<option>Van</option>
<option>Motorcycle</option>
</select>
</div>
<div>
<input type="checkbox">Vehicle 3
<select>
<option value=""></option>
<option>Car</option>
<option>Truck</option>
<option>Van</option>
<option>Motorcycle</option>
</select>
</div>
<br />
<br />
<button id="submit">submit data</button>

Do it like this, but first wrap all the form in a div and wrap texts like Vehicle 1 within a span. Then try the following code, click run to test
$('button').on('click', function() {
var errors = validateCouple($('#myForm'));
errors.length && alert(errors.join('\r\n'));
if (errors.length > 0) {
return false;
}
})
function validateCouple($el) {
var errors = [];
$el.find('div').each(function() {
var $div = $(this),
$cbx = $div.find('input:checkbox'),
$select = $div.find('select'),
$span = $div.find('span');
if ($cbx.prop('checked') && !$select.val()) {
errors.push("Please select a value for " + $span.html());
} else if ($select.val() && !$cbx.prop('checked')) {
errors.push("Please enable " + $span.html());
}
})
return errors;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myForm">
<div>
<input type="checkbox" checked="checked"><span>Vehicle 1</span>
<select>
<option></option>
<option>Car</option>
<option>Truck</option>
<option>Van</option>
<option>Motorcycle</option>
</select>
</div>
<div>
<input type="checkbox"><span>Vehicle 2</span>
<select>
<option>Car</option>
<option>Truck</option>
<option>Van</option>
<option>Motorcycle</option>
</select>
</div>
<div>
<input type="checkbox"><span>Vehicle 3</span>
<select>
<option>Car</option>
<option>Truck</option>
<option>Van</option>
<option>Motorcycle</option>
</select>
</div>
<br />
<br />
<button>submit data</button>
</div>

This code can help for your scenario
$("input,select").change(function() {
if($(this).prop("tagName") == "SELECT" && $(this).val() != "SELECT") {
$(this).siblings('input').prop("checked",true)
}
else if($(this).prop("tagName") == "SELECT" && $(this).val() == "SELECT") {
$(this).siblings('input').prop("checked",false)
} else if(($(this).prop("tagName") == "INPUT") && $(this).prop("checked") == true) { $(this).siblings('select').children('option:eq(1)').prop("selected","selected");
} else if(($(this).prop("tagName") == "INPUT") && $(this).prop("checked") == false) { $(this).siblings('select').children('option:eq(0)').prop("selected","selected");
}
})
<div>
<input type="checkbox">Vehicle 1
<select>
<option>SELECT</option>
<option>Car</option>
<option>Truck</option>
<option>Van</option>
<option>Motorcycle</option>
</select>
</div>
<div>
<input type="checkbox">Vehicle 2
<select>
<option>SELECT</option>
<option>Car</option>
<option>Truck</option>
<option>Van</option>
<option>Motorcycle</option>
</select>
</div>
<div>
<input type="checkbox">Vehicle 3
<select>
<option>SELECT</option>
<option>Car</option>
<option>Truck</option>
<option>Van</option>
<option>Motorcycle</option>
</select>
</div>
<br /><br />
<button>submit data</button>
</button>

Related

Is there any way where I can remove custom validations in HTML and add alerts?

I am trying to remove custom validations in HTML that occur with "required" attribute in the form. I do want the validations but I want to introduce "alerts" for the inputs.
<form>
<div>
<span>Search_word</span>
<input type="text" required></input>
</div>
<div>
<span>Frequency</span>
<select required>
<option disabled selected value></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div>
<button>Search</button>
</div>
</form>
Even when I am setting alerts with onlick() method on both, they are coming up twice. If I set up alert only on form, then It's not coming up for the dropdown option. And I am not able to figure out how to remove the custom validations. Is there a way I can turn them to alerts?
You can use classes on HTML to listen the event on JavaScript:
HTML:
<form>
<div>
<span>Search_word</span>
<input type="text" class="required"></input>
</div>
<div>
<span>Frequency</span>
<select class="required">
<option disabled selected value></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div>
<button id="search">Search</button>
</div>
</form>
JavaScript:
document.getElementById('search').onclick = function changeContent() {
var requireds = document.getElementsByClassName('required');
var error = 0;
for (var i = 0, len = requireds.length; i < len; i++) {
if (requireds[i].value == "") {
var error = error + 1;
}
}
if (error > 0){
if (error == 1) {
alert("There is a required field to inform");
} else {
alert("There are requireds fields to inform");
}
} else {
// ....
}
}
EDIT
In order to keep the HTML validation and introduce a alert message, you can use in HTML:
<form>
<div>
<span>Search_word</span>
<input type="text" required oninvalid="this.setCustomValidity('Enter the search word here'); alert('You have to enter a search word');"
oninput="this.setCustomValidity('')">
</div>
<div>
<span>Frequency</span>
<select class="required" required oninvalid="this.setCustomValidity('Select a frequency'); alert('You have to select a frequency');"
oninput="this.setCustomValidity('')">
<option disabled selected value></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div>
<button id="search">Search</button>
</div>
</form>

How to combine Selected price and input checkbox price Jquery?

i have a checkout form . where there are 2 fields are used o give total amount of checkout . 1 field is in select tag and second is input type check box i want when i select and option and checkbox there values should be combine to give total.
$(function() {
$('.price-input').change(function() {
var price = 0;
$('.price-input').each(function() {
if ($(this).is(":checked")) {
price += parseInt($(this).attr("value"), 10);
}
})
$("select.price").change(function() {
var selectedPrice = $(this).children("option:selected").val();
document.getElementById("totalPrice").innerHTML = selectedPrice;
});
$(".totalPrice").text(price);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6">
<div class="form-group">
<label for="exampleFormControlSelect1">#lang('Number of Words'):</label>
<select class="price" name="word_prices_id" required>
<option value="">#lang('Select Words')</option>
#foreach($wordPrice as $wPrice)
<option value="{{$wPrice->id}}">{{$wPrice->page_quantity}} words</option>
#endforeach
</select>
</div>
</div>
<input class="price-input" type="checkbox" name="upsell" value="12">
I added a class .ajx to both Select and input to handle changes made on both of their values in the same function !
$(document).on('change', '.ajx', function () {
if ($( "input.price-input:checked" ).is(":checked") && $("select.price").val()!==''){
var price = 0;
price += parseInt($("select.price").val(),10);
$('.price-input').each(function() {
if ($(this).is(":checked")) {
price += parseInt($(this).attr("value"), 10);
}
});
$(".totalPrice").empty().text(price);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6">
<div class="form-group">
<label for="exampleFormControlSelect1">Price:</label>
<select class="price ajx" name="word_prices_id" required id="exampleFormControlSelect1">
<option value="">Choose Price</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</div>
<input class="price-input ajx" type="checkbox" name="upsell" value="12">
<input class="price-input ajx" type="checkbox" name="upsell1" value="15">
<div class="totalPrice">
</div>

How to disable & Enable input element with html selector option

I want to make input element name="sellprice" enable if i select value sell option else input element will be disabled.
<select id="selling" name="selling">
<option value="">-- Choose --</option>
<option value="free">Open Source</option>
<option value="sell">I Wan't To Sell</option>
</select>
<div class="kd-title-show md-radio-inline">
<label for="4">Price :</label>
<input id="4" type="textbox" class="form-title" name="sellprice" placeholder="Min-$5 to Max-$100 " disabled>
</div>
Here is my Javascript Code, I have try this below code but it's not working.
$(document).ready(function(){
$("select[name='selling']").on('change',function(){
if($(this).val()== "free"){
$("input[name='sellprice']").prop("disabled",false);
}else{
$("input[name='sellprice']").prop("disabled",true);
}
});
});
Please have a look I hope it's useful for you.
$(document).ready(function(){
$("select[name='selling']").on('change',function(){
if($(this).val()== "sell"){
$("input[name='sellprice']").prop("disabled",false);
}else{
$("input[name='sellprice']").prop("disabled",true);
}
});
});
I want to make input element name="sellprice" enable
- that is not an input, it's a dropdown
If i select value sell option else input element will be disabled. - from your current explanation i understand that you want to disable the drop-down if the third option is selected
If the third option is selected, the drop-down will be disabled.
$(document).ready(function() {
$('#mounth').change(function() {
if( $(this).val() == "sell") {
$('#mounth').prop( "disabled", true );
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<select id="mounth" name="selling">
<option value="">-- Choose --</option>
<option value="free">Open Source</option>
<option value="sell">I Don't Want To Sell</option>
</select>
<div class="kd-title-show md-radio-inline">
<label>Price :</label>
<input id="textInput" type="textbox" class="form-title" name="sellprice" placeholder="Min-$5 to Max-$100 " disabled>
</div>
If you want to disable the input if the third option is selected, the following code will do it
$(document).ready(function() {
$('#mounth').change(function() {
if( $(this).val() == "sell") {
$('#textInput').prop( "disabled", true );
} else {
$('#textInput').prop( "disabled", false );
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<select id="mounth" name="selling">
<option value="" selected="selected">-- Choose --</option>
<option value="free">Open Source</option>
<option value="sell">I Don't want To Sell</option>
</select>
<div class="kd-title-show md-radio-inline">
<label>Price :</label>
<input id="textInput" type="textbox" class="form-title" name="sellprice" placeholder="Min-$5 to Max-$100 ">
</div>
<select id="mounth" onchange="myOnChangeFunction()" name="selling">
<option value="">-- Choose --</option>
<option value="free">Open Source</option>
<option value="sell">I Wan't To Sell</option>
</select>
<div class="kd-title-show md-radio-inline">
<label for="4">Price :</label>
<input id="4" type="textbox" class="form-title" name="sellprice" placeholder="Min-$5 to Max-$100 " disabled>
</div>
in js
<script>
function myOnChangeFunction() {
var val = document.getElementById("mounth").value;
if(val === "sell"){
document.getElementById('4').disabled = false;
}else{
document.getElementById('4').disabled = true;
}
}
</script>

How to perform an action only when a button is clicked in JavaScript

I have created a button with an action function as you can see below but the alert messages fires before I click the action button (click me). How can I make the alert messages appear only when I click the button (click me), and not when I choose "one" in the dropdown option value.
<p align="center">
<button style="height:50px;width:100px" onclick"=dropdownChange();">click me</button>
</p>
<p align="right">
<select dir="rtl" name="test2" id="experience" onchange="dropdownChange()" >
<option value="one"> one</option>
<option value="five">five</option>
<option value="six">six</option>
<option value="seven">seven</option>
<option value="" disabled selected>choose</option>
</select>
<font size="3"> number of experience</font>
</p>
<script>
function dropdownChange() {
var experience=document.getElementById("experience").value;
if(experience==="one") {
alert("ok");
document.getElementById('experience').value = "";
}
}
</script>
<p align="center"><button style="height:50px;width:100px" onclick=
dropdownChange();>click me </button></p>
<p align="right"><select dir="rtl" name="test2" id="experience"
>
<option value="one"> one</option>
<option value="five">five</option>
<option value="six">six</option>
<option value="seven">seven</option>
<option value="" disabled selected>choose</option>
</select> <font size="3"> number of experience</font>
</p>
<script>
function dropdownChange() {
var experience=document.getElementById("experience").value;
if(experience==="one") {
alert("ok");
document.getElementById('experience').value = "";
}
}
This should do the trick
Hi you forgot the " before and after dropdownChange().
< button style="height:50px;width:100px" onclick="dropdownChange();" >click me < / button>
There is nothing wrong with your code, it works fine as you can see below. Post some more code, the problem is somewhere else.
function dropdownChange()
{
var age = document.getElementById('age').value;
var major = document.getElementById('major').value;
var experience = document.getElementById('experience').value;
if ( age == "" || major == "" || experience == "" )
alert("fields cannot be empty!");
else
alert("Age: " + age + "\nMajor: " + major + "\nExperience: " + experience);
}
<!-- Sample elements -->
<input type="text" id="age" value="99" />
<input type="text" id="major" value="Physics" />
<input type="text" id="experience" value="Hmm" />
<p align="center"><button style="height:50px;width:100px"onclick="dropdownChange();" >click me </button></p>

Drop down text input option

I want a drop down element where user can select from available options or select enter value option which in turn allows to enter value.
I specifically want that user can enter value only when they select "Enter a value " option.
Here is what I have tried so far.
HTML-
<div class="ginput_container">
<select name="input_4" id="input_1_4" class="medium gfield_select" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<input type="text" value="None" class="holder" >
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var val = jQuery(this).val();
var enter = jQuery(this).parent().find('option:selected').text();
var x = jQuery(this).parent();
if (enter ==="Enter a value" || enter === "Enter value"){
var holder = x.find('.holder');
holder.val('');
holder.prop('disabled',false);
holder.focus();
} else {
x.find('.holder').val(x.find('option:selected').text());
}
});
JS fiddle
however it wont work properly if i click the enter value option again.
I think there are many plugins that do what you want but if you want to create your own, it's a basic and simple solution.
You can create a select and a textbox with display:none like this:
<select id="ddlDropDownList">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="-1">Enter Value</option>
</select>
<input id="txtTextBox" type="text" />
<style>
#txtTextBox{
display:none;
}
</style>
then try this JQuery:
$("#ddlDropDownList").change(function(){
if($(this).val() == '-1'){
$("#txtTextBox").fadeIn();
}else{
$("#txtTextBox").fadeOut();
}
});
Check JSFiddle Demo
I have forked your JSFiddle to http://jsfiddle.net/pwdst/4ymtmf7b/1/ which I hope does what you wanted to achieve.
HTML-
<div class="ginput_container">
<label for="input_1_4">Select option</label>
<select class="medium gfield_select" id="input_1_4" name="input_4" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<div>
<label class="hidden-label" for="input_1_4_other">Other value</label>
<input class="holder" id="input_1_4_other" disabled="disabled" name="input_1_4_other" placeholder="None" type="text" />
</div>
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var $this = jQuery(this);
var val = $this.val();
var holder = $this.parent().find('.holder');
if (val === "*"){
holder.val('');
holder.removeAttr('disabled');
holder.focus();
} else {
holder.val(this.options[this.selectedIndex].text);
holder.attr('disabled', 'disabled');
}
});
When the "Enter value" option is chosen then the input box is enabled, value set to an empty string, and it is focused. If another option is chosen then the text input is disabled again, and the text value from the select list is used.
Thanks guys
I guess i have found my answer
HTML-
<div class="ginput_container">
<select name="input_4" id="input_1_4" class="medium gfield_select" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<input type="text" value="None" class="holder" >
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var val = jQuery(this).val();
var enter = jQuery(this).parent().find('option:selected').text();
var x = jQuery(this).parent();
if (enter ==="Enter a value" || enter === "Enter value"){
var holder = x.find('.holder');
holder.val('');
holder.prop('disabled',false);
holder.focus();
jQuery(this).val("0"); // Change select value to None.
} else {
x.find('.holder').val(x.find('option:selected').text());
x.find('.holder').prop('disabled',true);
}
});
JS FIDDLE

Categories

Resources