jQuery to Validate an Input Text Control based on Radio Selection - javascript

How do I validate that the input text corresponding to the radio option is checked?
For example, using the image above:
If Contact 1's E-Mail radio option is selected, Contact 1's E-Mail text field cannot be blank, but Contact 1's Phone and US Mail text fields are still permitted.
If Contact 2's US Mail radio option is selected, Contact 2's US Mail text field cannot be blank, but Contact 2's Phone and E-Mail text fields are still permitted.
I have built the form above using the HTML below, but you can play with my Fiddle here: fiddle.
BEGIN UPDATE: I have a newer fiddle with better code here:
fiddle2
It has more instructions in the HTML and a closer attempt at my jQuery. For some reason, though, it still does not seem to be doing anything.
END UPDATE
I have tried naming the fields so that my jQuery can parse them, but that does not mean there is not a better way.
<body>
<form name="jp2code" action="#" method="POST">
<fieldset>
<legend>Contact 1</legend>
<span>
<input type="radio" id="group1_PhoneRadio" name="group1"/>
<label for="group1_PhoneText">Phone:</label>
<input type="text" id="group1_PhoneText" name="group1_PhoneText"/>
<br/>
<input type="radio" id="group1_EMailRadio" name="group1"/>
<label for="group1_EMailText">E-Mail:</label>
<input type="text" id="group1_EMailText" name="group1_EMailText"/>
<br/>
<input type="radio" id="group1_USMailRadio" name="group1"/>
<label for="group1_USMailText">US Mail:</label>
<input type="text" id="group1_USMailText" name="group1_USMailText"/>
</span>
</fieldset>
<fieldset>
<legend>Contact 2</legend>
<span>
<input type="radio" id="group2_PhoneRadio" name="group2"/>
<label for="group2_PhoneText">Phone:</label>
<input type="text" id="group2_PhoneText" name="group2_PhoneText"/>
<br/>
<input type="radio" id="group2_EMailRadio" name="group2"/>
<label for="group2_EMailText">E-Mail:</label>
<input type="text" id="group2_EMailText" name="group2_EMaiText"/>
<br/>
<input type="radio" id="group2_USMailRadio" name="group2"/>
<label for="group2_USMailText">US Mail:</label>
<input type="text" id="group2_USMailText" name="group2_USMailText"/>
</span>
</fieldset>
<div>
<input type="submit" name="submit" value="submit" />
</div>
</form>
</body>
What is the best way to write the jQuery?
I am new to jQuery, but I attempted my hand at it based on some Show/hide examples.
What I created below does not work, but hopefully indicates what I am trying to accomplish.
$(function() {
$("input[type='radio']").change(function() { // when a radio button in the group changes
var id = $(this).id;
var index = id.indexOf('group');
if (index == 0) { // is there a better way to do this?
var groupN_Len = 7; // Length of 'groupN_'
var radio_Len = 5; // Length of 'radio'
var preStr = id.substring(0, groupN_Len);
$"input[name*='preStr']".validate = null; // clear validation for all text inputs in the group
var postStr = id.substring(groupN_Len + 1, id.Length() + 1 - radio_Len); // extract Phone, EMail, or USMail
$(preStr+postStr+'Text').validate({ rules: { name: { required: true } } });
}
});
});

To make sure that the radiobutton is checked for each field, add attribute required="" in one of the radiobuttons for each fieldset.
demo

OK, whatever radio button is selected in the Contact Group's Contact Preferences, that corresponding text field is required.
Here is where I am so far on my jQuery checking:
EDIT:
Modified with tilda's important detail about adding '.' to the class name.
Added Required Attribute: how to dynamically add REQUIRED attribute to textarea tag using jquery?
Removed Required Attribute: jquery removing html5 required attribute
Final code works and looks like this:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script type="text/javascript">
$(function() {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("input[type='radio']").change(function() {
$('.'+$(this).attr('name')).each(function(index) {
$(this).removeAttr('required');
});
if($(this).is(':checked')) {
$('.'+$(this).attr('id')).each(function(index) {
$(this).prop('required',true);
});
}
});
$('#submit').click(function() {
$(this).validate();
});
});
Back to the HTML of the document: I did a lot of subtle editing to the text by creating specific ids and names for the radio buttons that matched up with the class names for the text controls.
Here is that end result:
<body>
<form name="jp2code" action="#" method="POST">
<div>For each field below, provide the Phone Number, E-Mail Address, and Street Address. <b>Indicate the preferred contact method using the radio button.</b></div>
<fieldset>
<legend>Contact 1</legend>
<span>
<input type="radio" id="group1_Phone" name="group1"/>
<label for="group1_Phone">Phone:</label>
<input type="text" name="group1_PhoneText" class="group1 group1_Phone" />
<br/>
<input type="radio" id="group1_EMail" name="group1"/>
<label for="group1_EMail">E-Mail:</label>
<input type="text" name="group1_EMailText" class="group1 group1_EMail" />
<br/>
<input type="radio" id="group1_USMail" name="group1"/>
<label for="group1_USMail">US Mail:</label>
<input type="text" name="group1_USMailText" class="group1 group1_USMail" />
</span>
</fieldset>
<fieldset>
<legend>Contact 2</legend>
<span>
<input type="radio" id="group2_Phone" name="group2"/>
<label for="group2_Phone">Phone:</label>
<input type="text" name="group2_PhoneText" class="group2 group2_Phone" />
<br/>
<input type="radio" id="group2_EMail" name="group2"/>
<label for="group2_EMail">E-Mail:</label>
<input type="text" name="group2_EMailText" class="group2 group2_EMail" />
<br/>
<input type="radio" id="group2_USMail" name="group2"/>
<label for="group2_USMail">US Mail:</label>
<input type="text" name="group2_USMailText" class="group2 group2_USMail" />
</span>
</fieldset>
<div>
<input type="submit" value="Send" id="submit"/>
</div>
</form>
</body>
Let me explain what is going on in the jQuery, using the HTML above:
When a radio button's checked state changes, each control with a class name that matches the radio button's name attribute has the required property removed.
If a radio button is checked (i.e. checked=true), then each control with a class name that matches the radio button's id attribute has the required property added.
Finally, the validator seems to have to be run on a single form control (not on individual text controls like I was doing).
Here is the sample Fiddle that I ended with: Fiddle v8
At tilda: You didn't say much, but what you did say helped a lot!

Related

populate 'today + x days' as form input value [duplicate]

I am trying to use the innerHTML method on an input tag and all i get back is a blank string. Here is the code i am useing.
javascript
function setName(ID){
document.getElementById('searchtitle').innerHTML = "Enter " + ID.innerHTML;
}
HTML
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)">Last Name</input><br/>
<input type="radio" name="searchtype" value="phonenumber" onclick="setName(this)">Phone Number</input><br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label><br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;"></input>
What is supposed to happen is depending on which radio button I pick the label for the input box should change. I can make the label.innerHTML=radio.value but the values are named for my php code and not formated nicely(ie. phonenumber vs. Phone Number) this is why I am trying to use the innerHTML of the radio button.
Any help I could get would be greatly appriciated.
you should embed input inside of label tag. input tag should closed by />. It's semantic HTML. When you do this clicking on label activate the input. InnerHTML only works for label then. It will return you label value.
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;" />
</label>
JavaScript:
console.log(document.getElementById('searchtitle').innerHTML); // returns 'Enter Last Name'
If you want the value of an input tag, you want to use .value.
First, add labels around your inputs. Second, use getName(this.parentNode). Finally, call innerText instead of innerHtml.
<html>
<head>
<script>
function setName(el){
document.getElementById('searchtitle').innerHTML = "Enter " + el.innerText;
}
</script>
</head>
<body>
<label><input type="radio" name="searchtype" value="name" onclick="setName(this.parentNode)"/>Last
Name</label><br/>
<label><input type="radio" name="searchtype" value="phonenumber" onclick="setName(this.parentNode)"/>Phone
Number</label><br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label><br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;"></input>
</body>
</html>
Complete edit.
Ok, I figured out what you were looking for. First off, you've got to fix your HTML (don't put text inside of an input... and don't next an input inside of a label).
<label for="test">Last Name</label>
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)" />
<br/>
<label for="test2">Phone Number</label>
<input type="radio" id="test2" name="searchtype" value="phonenumber" onclick="setName(this)" />
<br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label>
<br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;" />
JavaScript (in Jquery, for brevity):
function setName(elem)
{
$('#searchtitle').html('Enter ' + $('label[for="'+elem.id+'"]').html());
}
You have closed the Input tag improperly with </input>
this should be
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)"/>Last Name<br/>
<input type="radio" name="searchtype" value="phonenumber" onclick="setName(this)"/>Phone Number<br/>

HTML/ JavaScript radio button selections to output as summary of options

I'm trying to build a form that saves all of your selections of radio buttons and outputs as a summary upon submission. I am fairly new to JavaScript so please bear with me.
You are supposed to select between, let's say, three options per section. Depending on what was previously selected after you press Submit, it will open a lightbox and give you a summary of your choices before you submit the choices to be sent via email.
For what I have right now, there is only one section and three options to choose from.
HTML:
<div id="options">
<form method="get">
<label class ="rad">
<input type="radio" name ="O1" value="small"/>
<img src="img.jpg">
</label>
<label class ="rad">
<input type="radio" name ="O2" value="small"/>
<img src="img.jpg">
</label>
<label class ="rad">
<input type="radio" name ="O3" value="small"/>
<img src="img.jpg">
</label>
<input type="submit" value="SUBMIT"/>
</form>
</div>
JavaScript:
$(document).ready(function() {
$("#radio_submit").click(function (e) {
var checked_O1_radio = $('input:radio[name=O1]:checked').val();
var checked_O2_radio = $('input:radio[name=O2]:checked').val();
var checked_O3_radio = $('input:radio[name=O3]:checked').val();
if(checked_O1_radio===undefined || checked_O2_radio===undefined || checked_O3_radio===undefined)
{
alert('Please select a leather option then continue.');
}else{
alert('You Chose "' +checked_O1_radio);
}else{
alert('You Chose "' +checked_O2_radio);
}else{
alert('You Chose "' +checked_O3_radio);
}
});
});
Try this if i under stand your question correctly:
you can use same name then automatically only one will be selected and find the selected leather with a single check.
<label class ="rad">
<input type="radio" name ="O1" value="small"/>
</label>
<label class ="rad">
<input type="radio" name ="O1" value="medium"/>
</label>
<label class ="rad">
<input type="radio" name ="O1" value="large"/>
</label>
<input type="submit" value="SUBMIT" id = "Submitbutton"/>
$(document).ready(function() {
$("#Submitbutton").click(function (){
console.log($('input:radio[name=O1]:checked').val());
})
});
Please mark it as to answer if it helps you.

Dynamic Javascript Form Validation

Please bear with me as I am a beginner when it comes to JavaScript !
I have a dymamic form that pulls information from a database. For each line in the database there is a new row of form fields and the select name incorporates the id from the database - this is all on the same form e.g
<select name="supplier<%=objRst.fields("returnpartid")%>" id="supplier<%=objRst.fields("returnpartid")%>" onchange="validatelink3(<%=objRst.fields("returnpartid")%>)">
<select name="STOCKACTION<%=objRst.fields("returnpartid")%>" id="STOCKACTION<%=objRst.fields("returnpartid")%>" onchange="validatelink3(<%=objRst.fields("returnpartid")%>)">
<select name="stockreason<%=objRst.fields("returnpartid")%>" id="stockreason<%=objRst.fields("returnpartid")%>">
<select name="creditaction<%=objRst.fields("returnpartid")%>" id="creditaction<%=objRst.fields("returnpartid")%>" onchange="validatelink3(<%=objRst.fields("returnpartid")%>)">
<select name="rejectreason<%=objRst.fields("returnpartid")%>" id="rejectreason<%=objRst.fields("returnpartid")%>">
Users are currently missing out data when they are saving the record and I want to prevent this, The save button saves ALL of the records in one go so some lines will be totally blank if they have not yet been processed.
If a user has started to fill in the row but not completed all the information for that record then I need to stop the form submission.
Take a look at Parsley. I use this to validate my login and create user page of my website. Let me know what you think of it!
This is a great javascript tool that utilizes jQuery to validate different forms. Its really nice as you can have it validate several different things such as max and or min text length. It is very easy to implement because all you need to do is add the identifiers to the HTML element.
EDIT:
To avoid a link only answer, here is the code that could be helpful.
<form id="demo-form" data-parsley-validate>
<label for="question">Do you code? *</label>
<p>
<input type="radio" name="question" value="true" required /> Yes
<input type="radio" name="question" value="false" /> No
</p>
<label for="languages">If yes, in which language(s)?</label>
<input type="text" class="form-control" name="languages" data-parsley-conditionalrequired='[" [name=\"question1\"]:checked", "yes"]' data-parsley-validate-if-empty data-parsley-success-class="" data-parsley-conditionalrequired-message="This value is required since you are a programmer!" />
<label for="question">Do you eat dog food? *</label>
<p>
<input type="radio" name="question2" value="yes" required /> Yes
<input type="radio" name="question2" value="no" /> No
</p>
<label for="why">If no, why?</label>
<input type="text" class="form-control" name="why" data-parsley-conditionalrequired='[" [name=\"question2\"]:checked", "no"]' data-parsley-validate-if-empty data-parsley-success-class="" data-parsley-conditionalrequired-message="This value is required since you do not eat dog food!" />
<input type="submit" class="btn btn-default pull-right" />
</form>
<script type="text/javascript">
window.ParsleyConfig = {
validators: {
conditionalrequired: {
fn: function (value, requirements) {
// if requirements[0] value does not meet requirements[1] expectation, field is required
if (requirements[1] == $(requirements[0]).val() && '' == value)
return false;
return true;
},
priority: 32
}
}
};
</script>
<script type="text/javascript" src="../../dist/parsley.js"></script>
EDIT 2:
This is also a simple html file that could do something close to what I think that you want:
<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<input id="test" type="checkbox" id="chk"/>asdfad
<form>
<textarea></textarea>
<button onclick="myFunction()">asd</button>
<form>
<p>If the check box is check the thing is required and if the box is not check then it is not required. So tell your form to only save the rows that have the box checked?</p>
<script>
function myFunction() {
if(document.getElementById("test").checked){
document.getElementsByTagName("textarea")[0].setAttribute("required", "true");
}
else{
document.getElementsByTagName("textarea")[0].removeAttribute("required");
}
}
</script>
</body>
</html>

jQuery - Checking value of various input types

I have no idea what I'm doing wrong here. I have a form with radio buttons and simple text fields. I'm checking to see if there is a value within the form fields or if either of the radio buttons have been checked. If there is no value add a red color to the label. If they have a value I'm adding back the default black. But for some reason no matter if I put a value in the text field it stays red. Also kind of strange but if I check the first checkbox the black text appears. Any help is greatly appreciated.
JS Fiddle: http://jsfiddle.net/5Sacj/
<form name="headerForm">
<label id="gender" for="gender">Gender</label>
<input type="radio" name="customer" value="male" />Male
<input type="radio" name="customer" value="female" />Female
<br/>
<label for="fname">*First Name</label>
<input type="text" class="text" id="fname" name="fname" />
<br/>
<label for="fname">*Last Name</label>
<input type="text" class="text" id="lname" name="lname" />
<input id="submit" type="submit" name="submit" value="submit"
</form>
JQUERY
$(document).ready(function() {
$("#submit").on('click', function() {
$(":text, :radio").each(function() {
if($(this).val() === '' || !$(this).is(':checked')){
$(this).prev('label').css('color','red');
} else {
$(this).prev('label').css('color','black');
}
});
});
});
That is because you are using or operator ||.
It will execute even if one is true. Try using && or have separate if condition for both.

Get radio button value which is outside a form post

I have a form which has some radio buttons which is outside this form.The html is as follows
<input type="radio" id="radio1" name="radios" value="radio1" checked>
<label for="radio1">Credit Card</label>
<input type="radio" id="radio2" name="radios"value="radio2">
<label for="radio2">Debit Card</label>
<form method="post" action='./process.php'>
<label>name</label>
<input type="text"/>
<input type="submit" style="float:right" value="Pay Now"/>
</form>
When I press on the paynow button,i want to pass the value of button selected to the php of this form (process.php) .But I dont want to place the radio buttons inside the form.Is there any solution?
You could have a hidden value inside the form, onsubmit put the value of that radio button inside the hidden value
<input type="radio" name="test" value="a">a<br>
<input type="radio" name="test" value="b">b
<form>
<input type="hidden" name="test" id="hidden">
<submit onClick="transferData">
</form>
<script>
var transferData = function() {
var radioVal =$('input:radio[name=test]:checked').val()
$('#hidden').val(radioVal);
}
</script>
HTML5 supports an attribute called "form". You can use it to set the form for controls that are outside your form, like so:
<input type="radio" id="radio1" name="radios" value="radio1" checked>
<label form="myForm" for="radio1">Credit Card</label>
<input type="radio" id="radio2" name="radios"value="radio2">
<label form="myForm" for="radio2">Debit Card</label>
<form id="myForm" method="post" action='./process.php'>
<label>name</label>
<input type="text"/>
<input type="submit" style="float:right" value="Pay Now"/>
</form>
Note how id="myForm" is added to the form and form="myForm" is added to the radio-buttons. Hope that helped you.
Yeah, you could add a reference to jQuery, before the </body>. Then, using JQuery, you could select the checked radio button as follows:
var selected = $("input[type='radio']:checked");
if (selected.length > 0) {
selectedVal = selected.val();
}
The selectedVal parameter will hold the value you want.
The selection of the selected radio button should be done on the click event of submit button.
That could be done as follows:
$("input[type='submit']").click(function(){
// code goes here.
});
You must have a onsubmit attribute on your form, and inside, assign to a hidden field the selected radio button value.
Like this:
<form id='myForm' method="post" action='./process.php' onsubmit='getRadioButtonValue()'>
...
<input type="hidden" name="selectedRadioValue" />
</form>
function getRadioButtonValue(){
var radioValue = $('input[name=radios]:checked', '#myForm').val();
$('input[name='selectedRadioValue']').val(radioValue);
}
Put everything in the form. If you want to send all values. Add required attibute to your tags.
Other wise use jquery
<form id="test" method="POST">
<input type="text" id="name" required minlength="5" name="name"/>
<input type="password" id="pw" required name="pw"/>
<input id ="sub" type="submit"/>
</form>
<ul id="answer"></ul>
</body>
<script>
$("#sub").click(function(event){
event.preventDefault();
query = $.post({
url : 'check_ajax.php',
data : {'name': $('input[name=name]').val(), 'pw': $('#pw').val()},
});
query.done(function(response){
$('#answer').html(response);
});
});
</script>
All you need to do is to add the value of the option/input outside the form in the data
Use this onsubmit event!
$('input[name=radios]:checked').val()
Check the example

Categories