Changing one form value based on onChange of another with javascript - javascript

I can't seem to get this function to work out. I'm trying to change the "business" input value of my form based on an amount selected in the "amount" dropdown. What am I missing!!! I've been trying this for an hour.
<script type="text/javascript">
function chPy()
{
var businessvar = "paypals#ramatico.com";
if (document.forms['5'].amount.value > 11){
businessvar = "paypall#ramatico.com"
}
document.forms['5'].business.value = businessvar;
}
</script>
<form name="5">
<select name="amount" OnChange="chPy()">
<option value="na">Select</option>
<option value="1.00">$1</option>
<option value="5.00">$5</option>
<option value="10.00">$10</option>
<option value="15.00">$15</option>
<option value="20.00">$20</option>
<option value="25.00">$25</option>
</select>
<input name="business" type="text" value="">
</form>
Ok. The next step. I have about 100 of these forms on a page. Instead of creating one for each form, I'd like to have one script that changes based on which form is being changed with "onChange". Each of the forms on the page have values of the same name (but not ID) (they are for paypal). I think it will be ok if I can change the"formname" in the following: "document.forms['formname']" based on a variable populated by something like chPy("formname") etc..... I can't seem to get that to work either.

Removing the form reference would take care of both of your items.
<script type="text/javascript">
function chPy(oSelect)
{
var businessvar = "paypals#ramatico.com";
if (oSelect.form.amount.value > 11){
businessvar = "paypall#ramatico.com"
}
oSelect.form.business.value = businessvar;
}
</script>
<form name="5">
<select name="amount" OnChange="chPy(this)">
<option value="na">Select</option>
<option value="1.00">$1</option>
<option value="5.00">$5</option>
<option value="10.00">$10</option>
<option value="15.00">$15</option>
<option value="20.00">$20</option>
<option value="25.00">$25</option>
</select>
<input name="business" type="text" value="">
</form>

Problem is that you are using a number as form name.
Add some letters to the name and it will work:
<script type="text/javascript">
function chPy()
{
var businessvar = "paypals#XYZ.com";
if (document.forms['form5'].amount.value > 11){
businessvar = "paypall#XYZ.com"
}
document.forms['form5'].business.value = businessvar;
}
</script>
<form name="form5">
<select name="amount" OnChange="chPy()">
<option value="na">Select</option>
<option value="1.00">$1</option>
<option value="5.00">$5</option>
<option value="10.00">$10</option>
<option value="15.00">$15</option>
<option value="20.00">$20</option>
<option value="25.00">$25</option>
</select>
<input name="business" type="text" value="">
</form>

HTML:
<form name="form5">
<select name="amount">
<option value="na">Select</option>
<option value="1.00">$1</option>
<option value="5.00">$5</option>
<option value="10.00">$10</option>
<option value="15.00">$15</option>
<option value="20.00">$20</option>
<option value="25.00">$25</option>
</select>
<input type="text" name="business">
</form>
JavaScript:
var form5 = document.forms['form5'];
form5.amount.onchange = function() {
form5.business.value =
(this.value > 11 ? 'paypall' : 'paypals') + '#ramatico.com';
}
Live demo: http://jsfiddle.net/Fx7zh/
For multiple forms, you can use this JavaScript code:
for (var i = 0, l = document.forms.length; i < l; i++) {
document.forms[i].amount.onchange = function(i) {
this.form.business.value =
(this.value > 11 ? 'paypall' : 'paypals') + '#ramatico.com';
}
}
Live demo: http://jsfiddle.net/Fx7zh/2/

Related

How to condense hardcoded jQuery code to smaller generic code?

I have a code that works perfectly fine because it is hardcoded but extremely large. I would like to simplify this code to make it general and of course smaller. Does anybody know how to do this? Since it is so large I will shrink it down for this question.
var theform1 = $('#form1').find('.state option');
var stateForm1 = Object.keys(localStorage).filter(key => key.endsWith('-state1'));
var stateChoice1 = JSON.parse(localStorage.getItem(stateForm1));
var theform2 = $('#form2').find('.state option');
var stateForm2 = Object.keys(localStorage).filter(key => key.endsWith('-state2'));
var stateChoice2 = JSON.parse(localStorage.getItem(stateForm2));
var theform3 = $('#form3').find('.state option');
var stateForm3 = Object.keys(localStorage).filter(key => key.endsWith('-state3'));
var stateChoice3 = JSON.parse(localStorage.getItem(stateForm3));
if (localStorage.getItem(stateForm1)) {
$(theform1).empty();
$(theform1).val(stateChoice1).append(`<option value="${stateChoice1}">${stateChoice1}</option>`).trigger('window.load');
};
if (localStorage.getItem(stateForm2)) {
$(theform2).empty();
$(theform2).val(stateChoice2).append(`<option value="${stateChoice2}">${stateChoice2}</option>`).trigger('window.load');
};
if (localStorage.getItem(stateForm3)) {
$(theform3).empty();
$(theform3).val(stateChoice3).append(`<option value="${stateChoice3}">${stateChoice3}</option>`).trigger('window.load');
};
The HTML markup is as follows:
<form id="form1" autocomplete="off">
<select id="country1" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state1" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city1" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
<form id="form2" autocomplete="off">
<select id="country2" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state2" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city2" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
<form id="form3" autocomplete="off">
<select id="country3" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state3" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city3" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
Maybe you're looking for this compressed version:
$('#form1,#form2,#form3').each(function () {
var index = this.id.substring(this.id.length - 1, this.id.length);
var stateForm = Object.keys(localStorage).filter(key => key.endsWith('-state' + index));
var stateChoice = JSON.parse(localStorage.getItem(stateForm));
if (localStorage.getItem(stateForm)) {
var theform = $(this).find('.state option').empty();
theform.val(stateChoice)
.append(`<option value="${stateChoice}">${stateChoice}</option>`)
.trigger('window.load');
}
});
If you have more than 10 forms with the index increasing from 1 to 99 or 999... You can edit the way to name your form id to: form01 form02 form03 or form001 form002 form003...
Then, because all of the id names start with form, you can update the selectors like this:
Changing $('#form1,#form2,#form3') to $('[id^="form"]'). That selector means: selecting some element(s) which contains the id starts with form.
Lastly, if your form id following by 2 digits (form01), you update the line to get the index to:
var index = this.id.substring(this.id.length - 2, this.id.length);
You can do the same way for the ids following by 3 digits (form001):
var index = this.id.substring(this.id.length - 3, this.id.length);
Loop over all the select.state and get the number from the parent form.
Something like:
$('select.state').each(function() {
const $sel = $(this),
formNum = $sel.closest('form').attr('id').replace('form', ''),
stateForm = Object.keys(localStorage).find(key => key.endsWith(`-state${formNum }`)),
stateChoice = localStorage.getItem(stateForm);
if (stateChoice) {
$sel.append(new Option(stateChoice. stateChoice))
.val(stateChoice)
.trigger('window.load');
}
})
Note I changed filter() to find() for the keys since filter returns an array

Required attribute not working for select tag by onclick button

I am trying to alert a value when a user clicks the submit button. I gave the "required" attribute to both select tag but it is not working.
I want to alert a value when a user submits a button. Can anyone tell where i went wrong?
Code:-
function openWindow() {
var OR = document.getElementById("request").value;
var SZ = document.getElementById("sites").value;
var ORSZ = OR + SZ;
alert(ORSZ);
}
<select id="request" class="dropdownbox" required>
<option value="">Select</option>
<option value="ip">approve</option>
<option value="url">reject</option>
</select>
<select id="sites" class="dropdownbox" required>
<option value="">Select</option>
<option value="cp">Account</option>
<option value="sm">Demat</option>
</select>
<input type="button" onclick="openWindow()" value="Submit">
Here you go with a solution https://jsfiddle.net/1mydje82/1/
$('select').on('change', function(){
var required = false;
$('select').each(function(){
if($(this).val() === '')
required = true;
});
$('input[value="Submit"]').attr('disabled', required);
});
$('input[value="Submit"]').click(function(){
var OR = $("#request").val();
var SZ = $("#sites").val();
var ORSZ = OR + SZ;
alert(ORSZ);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="request" class="dropdownbox" required>
<option value="">Select</option>
<option value="ip">approve</option>
<option value="url">reject</option>
</select>
<select id="sites" class="dropdownbox">
<option value="">Select</option>
<option value="cp">Account</option>
<option value="sm">Demat</option>
</select>
<input type="button" value="Submit">
</form>
I've used jQuery. Initially your Submit button will be disabled.
Once you select both the drodown with values then only Submit button will be enabled.
Hope this will help you.
You can't rely on required attribute of <select>(because it's only work when form submits normally, and not supported in Opera anyhow).
You can make it happening like below:-
Example:-
function openWindow() {
var OR = document.getElementById("request").value;
var SZ = document.getElementById("sites").value;
if(OR =='' || SZ ==''){
alert('Please select values from both select-box'); return false;
}else{
var ORSZ = OR + SZ;
alert(ORSZ);
}
}
<form>
<select id="request" class="dropdownbox">
<option value="">Select</option>
<option value="ip">approve</option>
<option value="url">reject</option>
</select>
<select id="sites" class="dropdownbox">
<option value="">Select</option>
<option value="cp">Account</option>
<option value="sm">Demat</option>
</select>
<input type="button" onclick="openWindow()" value="Submit">
</form>

How to enable disable text input while making my function modular

Here is my script, what my goal is if other is selected in select, the other text input beside it will be enabled, this is what i've got so far, any approach will be really appreciated, I have 4 questions like this and I want it to be modular, best approach for doing my function to be reuseable.. How do I properly do this without any problem posting my data as 2 name inputs will generate 2 post variables in php.. T_T
<script type="text/javascript" charset="utf-8">
function validate()
{
var ddl = document.getElementById("cause_pain");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "OTHER")
{
document.getElementsByClassName("causepain")[0].removeAttribute("name");
document.getElementsByClassName("causepain1")[0].removeAttribute("disabled");
}
}
</script>
<form action="test.php" method="GET">
<select class="select causepain" id="cause_pain" name="cause_pain" onchange="validate()">
<option value="" selected="selected">Select Cause of Pain</option>
<option value="ARTHRITIS">ARTHRITIS</option>
<option value="RHEUMATISM">RHEUMATISM</option>
<option value="OLD AGE">OLD AGE</option>
<option value="ACTIVE LIFESTYLE WHEN YOUNGER">ACTIVE LIFESTYLE WHEN YOUNGER</option>
<option value="OTHER">OTHER</option>
</select>
<input class="causepain1" type="text" id="cause_pain" name="cause_pain" size="40" onkeyup="clean('this.id')" disabled>
<input type="submit" id="submit"/>
</form>
This method is reusable and pretty straight forward. Using data attributes, you could specify the element that needs to be shown on the specific option element. Also before showing any input element hide the elements that were attributed to the previous selection.
Example:
<form action="test.php" method="GET">
<select class="select causepain" id="cause_pain" name="cause_pain">
<option value="" selected="selected">Select Cause of Pain</option>
<option value="ARTHRITIS">ARTHRITIS</option>
<option value="RHEUMATISM">RHEUMATISM</option>
<option value="OLD AGE">OLD AGE</option>
<option value="ACTIVE LIFESTYLE WHEN YOUNGER">ACTIVE LIFESTYLE WHEN YOUNGER</option>
<option value="OTHER" data-show="cause_pain_other">OTHER</option>
</select>
<input class="causepain1" type="text" id="cause_pain_other" name="cause_pain" size="40"
onkeyup="clean('this.id')" disabled style="display: none;">
<input type="submit" id="submit"/>
</form>
<script type="text/javascript" charset="utf-8">
var selectedOpt;
function selectionChanged(e) {
if (selectedOpt && selectedOpt.dataset.show) {
var showEl = document.getElementById(selectedOpt.dataset.show);
showEl.disabled = true;
showEl.style.display = 'none';
}
selectedOpt = this.querySelector('[value="'+e.target.value+'"]');
if (selectedOpt.dataset.show) {
var showEl = document.getElementById(selectedOpt.dataset.show);
showEl.disabled = false;
showEl.style.display = 'block';
}
}
document.querySelector('select').addEventListener('change', selectionChanged);
</script>
Your selectedOpt should be an object if you're using multiple selects on the same page and then just add the element to the object with the id as an index:
var selectedOpt = {};
...
selectedOpt[this.id] = this.querySelector('[value="'+e.target.value+'"]');

Using Javascript to check form elements and enabling/disabling the search button

I need your help,
Using javascript, how could I add some sort of data form validation that would be two-fold:
1st Event, [OnKeyUp] attached to all of the input boxes
2nd Event, [OnChange] attached to all of the select boxes
Typical User Scenarios
If there is any data present in any of the input boxes and no selected option values then { enable the search button } else { keep the search button disabled }
If there are any selected option values who’s option value is not null and no data present in all of then { enable the search button } else { keep the search button disabled }
<!DOCTYPE html>
<html>
<head></head>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
</html>
var car=$('#car'); var fruits=$('#fruits');
var veggie=$('#veggie'); var number = $('#number');
$('select').change(function(){
validate();
});
$('input').keyup(function(){
validate();
});
function validate(){
if(($(veggie).val()!='' || $(number).val()!='') &&
$(car).val()=='' && $(fruits).val()==''){
$('#search').prop('disabled',false);
}else if($(veggie).val()=='' && $(number).val()=='' &&
($(car).val()!='' || $(fruits).val()!='')){
$('#search').prop('disabled',false);
}else{
$('#search').prop('disabled',true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
I'm not 100% sure, but it looks like you want to enable the button if only one of the select elements has a value or one of the input elements has a value, but not if both (or neither) do.
If that's the case then this should work, and it allows you you add as many elements to it as you need by adding IDs to the arrays at the top.
https://jsfiddle.net/j7by6bsz/
var selectInputIds = ['fruits', 'car'];
var textInputIds = ['veggie', 'number'];
function setButtonState() {
var hasVal = function(arr) {
for(var i = 0; i < arr.length; i++) {
if(document.getElementById(arr[i]).value) {
return true;
}
}
return false;
};
var hasSelectValue = function () {
return hasVal(selectInputIds);
}
var hasTextValue = function () {
return hasVal(textInputIds);
}
var theButton = document.getElementById('search');
var s = hasSelectValue();
var t = hasTextValue();
theButton.disabled = ((s && t) || (!t && !s)); // you can do this bit smarter, but this is explicit
}
(function attachStuff (arr, evt) {
function listenIn(arr, evt) {
for(var i = 0; i < arr.length; i++) {
document.getElementById(arr[i]).addEventListener(evt, setButtonState);
}
}
listenIn(selectInputIds, 'change');
listenIn(textInputIds, 'keyup');
}())
Your requirements could use some clarification around what happens if both input types have values though.

Form not validating before Submit (JavaScript)

I have a form written in JavaScript that works correctly when I submit. However, there is one conditional which I would like to be validated before the user hits the submit button. If the user chooses "None" on the dropdown menu, I want the other dropdown menu and textbox to be disabled before the user tries to submit. This is what I've done so far, but nothing seems to happen everytime I choose "None":
<form name="my_form" onsubmit="return submit()" action="/test" method="post">
<select id="month">
<option value="None">None</option>
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
<select id="day">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<input type="text" name="year" placeholder="Year" />
<input type="submit" value="Submit" />
</form>
<script>
function submit(){
var get_month_value = month.options[month.selectedIndex].text;
if(get_month_value == "None"){
document.getElementById("year").disabled = true;
document.getElementById("day").disabled = true;
return false;
}
else if(year == ""){
alert("Year must be filled out");
return false;
}
</script>
Where am I going wrong with this? Any help would be appreciated. Thanks.
Give form an ID and remove the onsubmit function:
<form id="my_form" name="my_form" action="/test" method="post">
Place the submit button outside the form and add the onclick function:
<input type="submit" value="Submit" onclick="submit();" />
Give year text field an ID:
<input type="text" id="year" name="year" placeholder="Year" />
Javascript:
function submit() {
var select = document.getElementById("month");
var get_month_value = select.options[select.selectedIndex].value;
var year = document.getElementById('year').value;
if ((get_month_value == "None") || (year == "")) {
alert("Please fill out the required fields");
} else {
document.getElementById("my_form").submit();
}
}
DEMO
HTML5 Date picker with "required" attribute(works):
<form id="dateForm" name="dateForm" action="/test" method="post">
Date: <input type="date" name="date" required />
<input type="submit" />
</form>
No need for JScript and html for dropdowns.
DEMO
Your code has the following errors:-
First of all you can't give your function the name submit in your form attribute.
You are missing } at the end of your function.
Your Input Text should have id=year not name.
Month is not defined.
year is not defined.
Change
these lines in your HTML:-
<form name="my_form" onsubmit="return validateForm()" action="/test" method="post">
<input type="text" id="year" placeholder="Year" />
Javascript:-
function validateForm(){
var month = document.getElementById('month');
var year = document.getElementById('year').value;
var get_month_value = month.options[month.selectedIndex].text;
if(get_month_value == "None"){
document.getElementById("year").disabled = true;
document.getElementById("day").disabled = true;
return false;
}
else if(year == ""){
alert("Year must be filled out");
return false;
}
}

Categories

Resources