Using javascript to make something required - javascript

As part of the form I have created users can select whether they want their order posted or to collect them. The appropriate div is shown when they make their choice from the radio buttons, i.e when they choose postage the inputs for them to enter their delivery address appears, and if they select collection a drop down box appears for them to pick the shop where they want to collect.
So am I trying to make it that the inputs or the drop down box be required by using JavaScript but what I am doing is not working and I can't see why as I have done similar things before and it has worked with no issues.
This is the html:
<p>Would you like postage(£7.25 extra) or to collect from one of our shops?</p>
<label class="checkbox-inline"></label>
<input type="radio" required name="delivery[]" onchange="calc()" class="deliv" id="delivery" data-descTarget="k_0" value="7.25">Postage
<label class="checkbox-inline"></label>
<input type="radio" name="delivery[]" class="deliv" onchange="calc()" id="collection" data-descTarget="k_1" value="0"/>Collection
<div id="k_0" class="desc">
<label>Please enter your delivery address</label>
<table border="0" cellpadding="0" id="table2">
<tr>
<td align="right">Name</font></td>
<td><input type="text" name="name1" id="name" size="15" tabindex="1"></td>
</tr>
<tr>
<td align="right">Email</font>
(Your confirmation will be sent here): </td>
<td><input type="text" name="email1" id="email" size="20" tabindex="1"></td>
</tr>
<tr>
<td align="right">Phone number:</td>
<td><input type="text" name="number1" id="number" size="15" tabindex="1"></td>
</tr>
<tr>
<td align="right">Address:</td>
<td><input type="text" name="address1" id="address" size="15" tabindex="1"></td>
</tr>
<tr>
<td align="right">Town:</td>
<td><input type="text" name="town1" id="town" size="15" tabindex="1"></td>
</tr>
<tr>
<td align="right">Postcode:</td>
<td><input type="text" name="postcode1" id="postcode" size="15" tabindex="1"></td>
</tr>
<tr>
<td align="right">County:</td>
<td><input type="text" name="county1" id="county" size="15" tabindex="1"></td>
</tr>
</table>
</div>
<div id="k_1" class="desc">
<div class="select-style">
<label>Collection Point</label>
<select id="collect" name="collect">
<option value="None" selected="selected">Select One</option>
<option value="Alford" >Alford</option>
<option value="Auld Toon" >Auld Toon</option>
<option value="Banff" >Banff</option>
<option value="Emmas">Emmas</option>
<option value="Insch" >Insch</option>
<option value="Kemnay" >Kemnay</option>
<option value="Market Place" >Market Place</option>
<option value="Mastrick"> Mastrick</option>
<option value="Meldrum Bakery" >Meldrum Bakery</option>
<option value="North Street" >North Street</option>
<option value="Rousay" >Rousay</option>
<option value="Seafield Street" >Seafield Street </option>
<option value="St Machar" >St Machar </option>
<option value="St Swithin" >St Swithin Street </option>
<option value="Stonehaven" >Stonehaven</option>
<option value="Torry" >Torry</option>
<option value="Keystore Old Aberdeen" >Keystore Old Aberdeen</option>
<option value="Keystore Old Meldrum" >Keystore Old Meldrum </option>
<option value="Highclere" >Highclere</option>
</select>
</div>
</div>
<input type='submit' id='submit' name="submit" onClick="checkValue()" class="submit" value='Submit' />
This is the script that hides the divs until the appropriate radio button is selected:
<script type="text/javascript">
$(document).ready(function() {
$("div.desc").hide();
$("input[name$='delivery[]']").click(function() {
var choice = $(this).attr("data-descTarget");
$("div.desc").hide();
$("#" + choice).show();
});
});
</script>
This is what I have tried for making the fields required:
function checkValue() {
if (document.getElementById('delivery').checked) {
document.getElementsByName("name1").required = true;
document.getElementsByName("email1").required = true;
document.getElementsByName("number1").required = true;
document.getElementsByName("address1").required = true;
document.getElementsByName("town1").required = true;
document.getElementsByName("postcode1").required = true;
document.getElementsByName("county1").required = true;
document.getElementById("collect").required = false;
} else if (document.getElementById('collection').checked) {
document.getElementById("collect").required = true;
document.getElementsByName("name1").required = false;
document.getElementsByName("email1").required = false;
document.getElementsByName("number1").required = false;
document.getElementsByName("address1").required = false;
document.getElementsByName("town1").required = false;
document.getElementsByName("postcode1").required = false;
document.getElementsByName("county1").required = false;
}
}
Where have I gone wrong with the checkValue script?

I've used JQuery here as you are using it already, but this function will update the inputs like you are looking for and to make it easier to update and add/remove fields I used an array of input id's to loop through rather than hardcoding each one as you are.
function updateRequiredFields (isCollecting){
var deliveryFields = ["name","email","number", "address", "town", "postcode", "county"];
for(var x = 0; x < deliveryFields.length; x++){
$("#" + deliveryFields[x]).attr("required", !isCollecting);
}
$("#collect").attr("required", isCollecting);
}
Edit: Update for comment.
Your Inputs aren't wrapped inside of a form, after wrapping them in a form it works as intended.

I'd say its because you're sending info to an attribute of an array instead of the element itself. When you ask JS to receive true for the required attribute, you're sending to the array, since getElementsByName returns a collection of elements. You gotta iterate through those.
function changeRequireForAll(els, required) {
for(var i = 0; i < els.length; i++) {
if(els[i]) {
els[i].required = required;
//you could do els[i].setAttribute('required', required); too
}
}
}
//And you call it as
changeRequireForAll(document.getElementsByName("county1"), false);
That way, you just send your element collection and it will change all instances that matches your query. Even if your collection returns a single element, its still a single-item-array

Related

How can I add/remove select boxes from DOM when all select boxes have one name so that upon Submit I get value from active select box?

TL;DR: I want to be able to make a selection using currently-active HTML select box, when I have multiple select boxes with the same name, but only one of them is to be active at any one time.
--
My question is this - I have multiple filename select boxes, that upon submit, always send the value of the last select box that is at the bottom of HTML that has filename name in HTTP Request. I want to find a way to send only the filename that is associated with the currently-active a_XX_row box, and not any others.
i.e. I select id of 40, I should only see the box that says "A-40 Designer and Specs", and not the 800 box. When I press submit I want POST['filename'] to have the "A-40 Designer and Specs", but instead I always get the "A-800 Designer E.xlsm", because it is the last select in the HTML file.
$('#modelid').on('change', function() {
if (this.value == 40)
$('.a_40_row').show();
else
$('.a_40_row').hide();
if (this.value == 800)
$('.a_800_row').show();
else
$('.a_800_row').hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--
<option value="40">40
<option value="800">800
</select>
</td>
</tr>
<tr class="a_40_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option selected>A-40 Designer and Specs B.xlsm</option>
<option>A-40 Designer and Specs A.xlsm</option>
</select>
</td>
</tr>
<tr class="a_800_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option>A-800 Designer E.xlsm</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>
don't show/hide selects form.
you just need to update the second select when the first is changed
the way to do that:
const
myForm = document.forms['my-form']
, filenames =
[ { model: '40', cod: 'A-40-B', fn:'A-40 Designer and Specs B.xlsm' }
, { model: '40', cod: 'A-40-A', fn:'A-40 Designer and Specs A.xlsm' }
, { model: '800', cod: 'A-800-E', fn:'A-800 Designer E.xlsm' }
]
myForm.modelid.onchange = () =>
{
myForm.filename.innerHTML = ''
filenames
.filter(x=>x.model===myForm.modelid.value)
.forEach( filename=>
{
myForm.filename.add( new Option(filename.fn,filename.cod))
}
)
}
select,
button {
display : block;
float : left;
clear : left;
margin : .3em;
}
select {
min-width : 8em;
padding : 0 .3em;
}
<form name="my-form">
<select name="modelid" >
<option value="" selected disable >--select--</option>
<option value="40" > 40 </option>
<option value="800" > 800 </option>
</select>
<select name="filename"></select>
<button type="submit">submit</button>
</form>
Two options,
Enable/disable the element as you show it.
Populate one field with what you need.
Option 1 :
$('#modelid').on('change', function() {
//Set visibility
$('.a_40_row').toggle(this.value == 40);
//Toggle disabled
$('.a_40_row [name=filename]').prop("disabled", this.value != 40);
$('.a_800_row').toggle(this.value == 800)
$('.a_800_row [name=filename]').prop("disabled", this.value != 800);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--</option>
<option value="40">40</option>
<option value="800">800</option>
</select>
</td>
</tr>
<tr class="a_40_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename" disabled>
<option selected>A-40 Designer and Specs B.xlsm</option>
<option>A-40 Designer and Specs A.xlsm</option>
</select>
</td>
</tr>
<tr class="a_800_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename" disbled>
<option>A-800 Designer E.xlsm</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>
Option 2 : - This uses HTML 5 which has issues in IE 10 and less
$('#modelid').on('change', function() {
$(".row").show();
var selVal = $(this).val();
//Go through the options
$("[name=filename] option").each(function(){
//Dont use jquerys data here, it will convert to a number when it can
//Get array of values where can display from the data attribute
var arrDisplay = this.dataset.display.split(",");
//Add the hidden property if not contained in array -- wont work in IE 10 and older
$(this).prop("hidden", !arrDisplay.includes(selVal));
//Set a default
$(this).prop("selected", $(this).data("optiondefault") && !arrDisplay.includes(selVal) )
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--</option>
<option value="40">40</option>
<option value="800">800</option>
</select>
</td>
</tr>
<tr class="row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option data-display="40" data-optiondefault="true">A-40 Designer and Specs B.xlsm</option>
<option data-display="40">A-40 Designer and Specs A.xlsm</option>
<option data-display="800" data-optiondefault="true">A-800 Designer E.xlsm</option>
<option data-display="40,800">Hybrid</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>

How do you reference a checkbox array name value?

I have a sequence of checkboxes and associated select lists. If the checkbox is checked I need to take the value of the corresponding select option and then change the total, but I can't seem to reference this value. Here is a simplified version of the HTML code:
<table>
<tr>
<td>
<input type="checkbox" name="checkboxCK[]" id="checkboxAR1" class="check" />
</td>
<td>
<select name="addonR[]" class="select-colour">
<option value="50">1 ($50)</option>
<option value="100">2 ($100)</option>
<option value="150">3 ($150)</option>
<option value="200">4 ($200)</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="checkboxCK[]" id="checkboxAR2" class="check" />
</td>
<td>
<select name="addonR[]" class="select-colour">
<option value="50">1 ($50)</option>
<option value="100">2 ($100)</option>
<option value="150">3 ($150)</option>
<option value="200">4 ($200)</option>
</select>
</td>
</tr> <tr>
<td>
<input type="checkbox" name="checkboxCK[]" id="checkboxAR3" class="check" />
</td>
<td>
<select name="addonR[]" class="select-colour">
<option value="50">1 ($50)</option>
<option value="100">2 ($100)</option>
<option value="150">3 ($150)</option>
<option value="200">4 ($200)</option>
</select>
</td>
</tr>
<table>
$<span id="theTotalAmount">150</span>
And the javascript code:
$("input.check:checkbox").click(function(){
//run through allcheckboxes that are checked and pull corresponding select option value
for (var i = 0; i < document.getElementsByName('checkboxCK[]').length; i++)
{
//get the value of the selected option
var s = document.getElementsByName('addonR['+i+']');
var theAmount = s.options[s.selectedIndex].value;
console.log(theAmount);
//check the checkbox is checked and if so add the corresponding select value
if(document.getElementsByName('checkboxCK['+i+']').checked)
{
totalCost = totalCost+document.getElementsByName('addonR['+i+']').value;
}
}
//rewrite the html for total amount
document.getElementById("theTotalAmount").innerHTML = totalCost;
});
I am struggling to reference the s variable.. It keeps being undefined. Can anyone see why?
Or is there a better way to achieve what I am trying to do?
The names of the checkboxes don't have a number between the square brackets in the HTML. You shouldn't put one there with your JavaScript.
document.getElementsByName('addonR[]') will give you an (array-like) HTML Collection of all the elements with that name.
Write
var s = document.getElementsByName('addonR[]')[i];

How to make a form-based formatted text generator with JS?

I'd like to make a Javascript-based web form that would generate formatted output (BBcode to be exact) based on the inputs and selections done by the user. The output should be displayed on a separate text field for easy copying and usage.
I do know how to make the HTML-based form and how the result should look like, but I'm struggling with the JavaScript code needed to generate and format it.
EDIT: I have created the HTML form below, using this example.
Now I would like to know how to use JavaScript to output text and format it to suit my needs.
<form name="example" action="#" onsubmit="checkit(); return false">
<table class="form">
<tr>
<td>Your name</td>
<td><input name="yourname" /></td>
</tr>
<tr>
<td>Who did you punish?</td>
<td><input name="punishedname" /></td>
</tr>
<tr>
<td>Punishment?</td>
<td><select name="punishment">
<option value='' selected="selected">--- Select ---</option>
<option value="mute">mute</option>
<option value="kick">kick</option>
<option value="ban">ban</option>
<option value="ipban">IP-ban</option>
</select>
</td></tr>
<tr>
<td>For how long?</td>
<td><input name="time" />
<select name="timeunit">
<option value='' selected="selected">--- Select ---</option>
<option value="minutes">minutes</option>
<option value="hours">hours</option>
<option value="days">days</option>
<option value="weeks">weeks</option>
</select></td>
</tr>
<tr><td colspan="2"><input type="submit" value="Submit form" /><br />
<input type="reset" /></td></tr>
<tr><td colspan="2"><textarea cols="30" rows="7" name="output">Output will be written here</textarea></td></tr>
</table>
You need javascript/PHP or any other languages.
To do in javascript ..
First make provide id or name attribute to you input fields and other form elements.
create a function which will be called by submitting form.
Collect values from form fields to variables
var name = document.getElementById("id_attribute_value").value; //Collects value using id attribute
var name = document.getElementByName("name_attribute_value").valueOf; //Collects value using name attribute
now to display values (say in textarea)
document.getElementById("id_attribute").value = name + punishment + other_vars; //This will put all the collected values in that textarea
To do something like this in php
Follow up this link
http://www.w3schools.com/php/php_form_validation.asp

Hide elements and unrequiring them based on dropdown selection

I have seen examples of this using jquery or javascript, but I am not experienced with either of these at all so everything I try fails. I need all of the required fields hidden and 'unrequired' if that's a word, if someone chooses the option "PayPal".
<tr>
<td colspan="2"><h4>Please enter payment method.</h4></td>
</tr>
<tr>
<td class="required" colspan="2">
<label>
Card Type <span>*</span>
<select name="CardType" id="CardType">
<option value="" selected="selected">--Please Select--</option>
<option value="Amex">American Express</option>
<!--<option value="Discover">Discover</option>-->
<option value="MasterCard">MasterCard</option>
<option value="PayPal">PayPal</option>
<option value="Visa">Visa</option>
</select>
</label>
</td>
</tr>
<tr>
<td class="required" width="50%">
<label>
Card Number <span>*</span> <br />
<input type="text" name="CardNumber" id="CardNumber" class="text" maxlength="16" onkeypress="return isNumberKey(event)" />
<em> </em>
</label>
</td>
<td class="required" width="50%">
<label>
Security Code <span>*</span> <br />
<input type="text" name="CardCode" id="CardCode" class="text" maxlength="5" onkeypress="return isNumberKey(event)" />
<em>What's this?</em>
</label>
</td>
</tr>
<tr>
<td class="required">
<label>
Expiration Month <span>*</span>
<select name="CardMonth" id="CardMonth">
<option value="" selected="selected">--Month--</option>
<option value="01">January - (01)</option>
<option value="02">February - (02)</option>
<option value="03">March - (03)</option>
<option value="04">April - (04)</option>
<option value="05">May - (05)</option>
<option value="06">June - (06)</option>
<option value="07">July - (07)</option>
<option value="08">August - (08)</option>
<option value="09">September - (09)</option>
<option value="10">October - (10)</option>
<option value="11">November - (11)</option>
<option value="12">December - (12)</option>
</select>
</label>
</td>
<td class="required">
<label>
Expiration Year <span>*</span>
<select name="CardYear" id="CardYear">
<option value="" selected="selected">--Year--</option>
<?
$yToday = date("Y");
$yLimit = $yToday + 10;
for($y=$yToday; $y<$yLimit; $y++)
print "<option value='$y'>$y</option>\n";
?>
</select>
</label>
</td>
</tr>
I've looked at the following posts for guidance but they are just confusing me:
Show hide elements based on ID from select dropdown javascript and
jQuery show/hide text field based on a dropdown selection value and a radiobutton
Nothing that I look for seems to have the capability of removing required fields based on that selection. I still need them to be required if the user chooses any of the credit card options, just not for PayPal. Can someone please post a link that they think is the best course for this situation or some sample code I can look at?
First, you may be using the <label> tag incorrectly. In my jsFiddle demo, I wanted to check each label's text in order to not hide the Card Type cell. However, the label surrounds not only the text, but also the <select> element itself. This is not how the label tag should be used. In an updated demo, I will still NOT the Card Type cell, but you will see the kludge that must be used (.split method) to determine the name of the label.
Next, I suggest making the fields *required, and not the table cells.
When validating your code, it is more difficult to determine if a field is required if you must always look at the corresponding table cell attributes. Much simple just to look at the field's own attributes. However, here is something that addresses your question as it is:
jsFiddle Demo
$('#CardType').change(function() {
if ($(this).val() == 'PayPal'){
$('.required').each(function() {
$(this).removeClass('required');
$(this).hide();
});
}
});
Revised example to show hiding all cells except the Card Type cell:
jsFiddle Demo 2
var lbl;
$('#CardType').change(function() {
if ($(this).val() == 'PayPal'){
$('.required').each(function() {
lbl = $(this).find('label').text().split('*')[0];
if (lbl != 'Card Type '){
$(this).removeClass('required');
$(this).hide();
}
});
}
});
And one more example to demonstrate unhiding and restoring the required class when select is changed to something else. Note that it was necessary to add an additional class ("req_poss") to each <td> element for which the REQuired class may POSSibly need to be re-added:
jsFiddle Demo 3
var lbl;
$('#CardType').change(function() {
if ($(this).val() == 'PayPal'){
$('.required').each(function() {
lbl = $(this).find('label').text().split('*')[0];
if (lbl != 'Card Type '){
$(this).removeClass('required');
$(this).hide();
}
});
}else{
$('.req_poss').each(function() {
$(this).addClass('required').show();
});
}
});
add event $('#CardType').on('change',function() {});
and in this function get all the inputs and with the function $.each() if the value of select is paypal removeAttr() 'required' for all or just hide() it or whatever You want.
Sorry, I'm barely following what you're saying, the only things required are what you make required by not allowing other things to happen until there is input in them, that's easily taken care of by changing the attributes to remove "required" at the same time you hide other things
$("#CardType").change(function(){
if ($("#CardType).value()=="PayPal"){
$("fieldYouWantToHide).hide();
}
});

Javascript replace "other" value with input from text field

I have the following form that I am working on...
When a user choses an option from a radio group a div is displayed with a multiple selection list. If one of those selections is "other" a text box is dislayed allowing the user to input the information.
How do I get the form to return the selections from the multiple selection list while replacing the "other" value with the value of the text input field??
I'vespent countless hours searching google and this website and while I've found some similar solutions, none are for multiple selections and none fit my needs.
This is what I have so far for the form:
<form method="post" action="send_email.asp" onsubmit="return Form_Validator (this)"
name="form2" id="form2" >
<tr>
<td>Product Type: <br />
<input name="ProductType" type="radio" value="Network" tabindex="1"
onclick="setVisibility('NetworkProducts','inline'); setVisibility
('CPEProducts','none');"/>
Network<br />
<input name="ProductType" type="radio" value="Network and CPE" tabindex="2"
onclick="setVisibility('NetworkProducts','inline'); setVisibility
('CPEProducts','inline');"/>
Network and CPE<br />
<input name="ProductType" type="radio" value="CPE Only" tabindex="3"
onclick="setVisibility('NetworkProducts','none'); setVisibility
('CPEProducts','inline');"/>
CPE Only<br/>
<div id="NetworkProducts" align="left">
Network Product Sold <span class="style2">*</span>
<select name="NetProductSold" size="3" multiple="MULTIPLE"
id="NetProductSold" onchange="showothernet(this.form);">
<option value="Prod1">Prod1</option>
<option value="Prod2">Prod2</option>
<option value="Prod3">Prod3</option>
<option value="Prod4">Prod4</option>
<option value="Prod5">Prod5</option>
<option value="Prod6">Prod6</option>
<option value="Prod7">Prod7</option>
<option value="Prod8">Prod8</option>
<option value="Prod9">Prod9</option>
<option value="Prod10">Prod10</option>
<option value="Other">Other</option>
</select>
</div>
<blockquote>
<div id="OtherNetworkProducts" align="left" >
If other, Please specify: <input name="OtherNetProductSold"
type="text" id="OtherNetProductSold" size="50" onblur="setFocus(this);" >
</div>
</blockquote>
<div id="CPEProducts" align="left">
CPE Product Sold <span class="style2">*</span>
<select name="CPEProductSold" size="3" multiple="multiple"
id="CPEProductSold" onchange="showothernet(this.form);" >
<option value="CPE1">CPE1</option>
<option value="CPE2">CPE2</option>
<option value="CPE3">CPE3</option>
<option value="CPE4">CPE4</option>
<option value="CPE5">CPE5</option>
<option value="CPE6">CPE6</option>
<option value="CPE7">CPE7</option>
<option value="Other">Other</option>
</select>
</div>
<blockquote>
<div id="OtherCPEProducts">
If other, Please specify: <input name="OtherCPEProductSold" type="text"
id="OtherCPEProductSold" size="50" >
</div>
</blockquote>
</form>
And this is what I have for the javascript:
<script Language="JavaScript"><!--
function setVisibility(id, visibility) {
document.getElementById(id).style.display = visibility;
}
function showothernet (form)
{
for (var j = 0; j < form.NetProductSold.length; j++)
{
if (form.NetProductSold.options[j].selected)
{
if(form.NetProductSold.options[j].value == "Other")
{
setVisibility('OtherNetworkProducts','inline');
}
else
{
setVisibility('OtherNetworkProducts','none');
}
}
}
for (var i = 0; i < form.CPEProductSold.length; i++)
{
if (form.CPEProductSold.options[i].selected)
{
if(form.CPEProductSold.options[i].value == "Other")
{
setVisibility('OtherCPEProducts','inline');
}
else
{
setVisibility('OtherCPEProducts','none');
}
}
}
}
function setFocus(form)
{
var process = form.OtherNetProductSold.value;
form.NetProductSold.options[10].value = process
alert (form.NetProductSold.options[10].value);
}
//--></script>
The form functions the way I want it to, when the user clicks "Network" or "Network and CPE" and list appears for the Network products, then if the "other" option is one of the selected options, the text field for other is displayed.
The problem is how to replace that "other" value from the multiple selection with the input from the text field.
PLEASE HELP!
Thanks in advance!
The text showed to the user is between <option> and </option>. So, set it as .innerHTML instead (it changes the text between):
form.NetProductSold.options[10].innerHTML = process;
Secondly, you have:
<input name="OtherNetProductSold"
type="text" id="OtherNetProductSold" size="50" onblur="setFocus(this);" >
while your setFocus accepts a form. So, setFocus(this.form) you should use.
http://jsfiddle.net/pimvdb/nMkvb/

Categories

Resources