Limit to One When the Checkbox is Checked - javascript

I have a Form where I want to limit the Data from my Drop Downlist when the checkbox is checked
So that When i Save theres a Message window that will Appear and Let the user know that he/she checked the checkbox for the Same Drop Down Value
using (Html.BeginForm("Save", "Worker", FormMethod.Post, new { id = "contactForm" }))
{
<input type="hidden" id="workerId" name="workerId" value="#workerId" />
<p>
<label for="ddlContactType">
Contact Type</label>
<span>
#Html.DropDownList("ddlContactType", new SelectList(ViewBag.ContactTypeList, "ID", "Display_Value", workerContactType), "[Please Select]",
new Dictionary<string, object>
{
{"class","validate[required] inputLong"}
})
</span>
</p>
<p>
<label for="txtContactValue">
Contact Value</label>
<span>
<input type="text" id="txtContactValue" name="txtContactValue" class="validate[required] inputLong" value="" />
<input type="checkbox" name="chkWorkerIsPrimary" id="chkWorkerIsPrimary" value="true"
checked="checked" />
<label>
Is Primary?</label>
</span>
</p>
<p>
<span>
<input type="submit" id="btnAdd" class="styledButton" value="Add" />
</span>
</p>
}
</div>
I need the Validation written in Javascript but i dont know how to start :(
Thanks

Jquery:
if($('#chkWorkerIsPrimary').is(':checked')){
//Your code
}
.is(':checked') if the user has checked the checkbox returns true, else return false
or javascript:
if ($("[name=chkWorkerIsPrimary]:checked").length == 0){
//your code
}

Related

How to remove required attribute after select

I did an asset delivery system so there are two options for the user to select which is NOT YET DELIVERED and ALREADY DELIVERED.
I used javascript to allow date input to display if the user selects ALREADY DELIVERED. I added required for the calendar so that the user cannot submit the details if user doesn't choose a date and it worked perfectly.
However,when the user selects NOT YET DELIVERED, the system doesn't display the calendar and therefore cannot submit the form due to the calendar being required.
I wanted the calendar to be required if the user selects ALREADY DELIVERED but not for NOT YET DELIVERED.
Thank you in advance.
$(function() {
with name = 'status') $(document).on("change", "input[name='status']", function() {
console.log("Testing");
var checkedValue = $(this).val();
console.log(checkedValue);
else;
checkedValue == 1 ? $(".box").show() : $(".box").hide();
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="alignright">
<div>
<br />
<label>
<input type="radio" name="status" value="0" required /> Not yet
delivered
</label>
<br />
<label>
<input type="radio" name="status" value="1" required /> Already
delivered
</label>
</div>
</span>
<span class="alignleft">
<div class="box">DELIVERY DATE<input type="date" name="deliverydate"
id="deliverydate" required="" />
</div>
</span>
Instead of setting the required value on the date input, set it depending on which option the user selects. You can do this at the same time as hiding/showing it.
$(document).on("change", "input[name='status']", function() {
var checkedValue = $(this).val();
if(checkedValue == 1){
$(".box").show();
$(".box").prop("required",true);
} else {
$(".box").hide();
$(".box").prop("required",false);
}
console.log($(".box").prop("required"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="alignright">
<div>
<br />
<label>
<input type="radio" name="status" value="0" required /> Not yet
delivered
</label>
<br />
<label>
<input type="radio" name="status" value="1" required /> Already
delivered
</label>
</div>
</span>
<span class="alignleft">
<div class="box">DELIVERY DATE<input type="date" name="deliverydate"
id="deliverydate" />
</div>
</span>
You can do it this way:
$(function() {
with name='status')
$(document).on("change", "input[name='status']", function() {
console.log("Testing");
var checkedValue = $(this).val();
console.log(checkedValue);
else;
if(checkedValue == 1) {
$(".box").show();
$('input#deliverydate').prop('required',true);
} else {
$(".box").hide();
$('input#deliverydate').prop('required',false);
}
})
});
Hope it helps.

HTML Session data isn't saving and unwantly clears page

So i can save one question but when i add more it doesnt work. I though i could just add on to postquestion function copy and paste and just change 16 to 15 but i guess that is to easy
I need to save about 16 total questions with 4 choices each question, and the selected radio is the correct answer.
Also is there a way to save selected radio buttons into session and local storage?
function postQuestion() {
var obj = {
question: document.getElementById("question16").value,
choice62: document.getElementById("choice62").value,
choice63: document.getElementById("choice63").value,
choice64: document.getElementById("choice64").value,
choice65: document.getElementById("choice65").value
}
try {
sessionStorage.setItem("data", JSON.stringify(obj));
} catch (error) {
alert("Enable Session storage");
}
return false;
}
function PreviewImage16() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage16").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview16").src = oFREvent.target.result;
sessionStorage.setItem("image", oFREvent.target.result);
};
};
<div>
Enter Question 16:
<input type="text" id="question16" name="question16">
<br>
<br> Next, add a correct answer and several incorrect answers for your question.
<br>
<form onsubmit="return postQuestion()">
<p>
<input type="radio" name="choice62" value="62">
<label>
<input id="choice62" size="50">
</label>
</p>
<p>
<input type="radio" name="choice63" value="63">
<label>
<input id="choice63" size="50">
</label>
</p>
<p>
<input type="radio" name="choice64" value="64">
<label>
<input id="choice64" size="50">
</label>
</p>
<p>
<input type="radio" name="choice65" value="65">
<label>
<input id="choice65" size="50">
</label>
</p>
<p>
<button type="submit"> Submit</button>
</p>
<br>
<img id="uploadPreview16" style="width: 100px; height: 100px;" />
<input id="uploadImage16" type="file" name="myPhoto16" onchange="PreviewImage16();" />
</div>

Save Data to Localstorage and use it to populate fields after submit

I have optin popup of two steps, first step is to capture email and name, when user click submit the data is captured, and another popup appears, the new popup has a form with more fields to get more info, plus email and name field.
what I want to do is to automatically populate the email and name field from first popup and hide them with display:none so user can't see them, after submit the data is captured again (all goes to activecampaign).
the two forms works just fine, what is not working is saving the data and calling it when needed
here is the js I'm using
jQuery(function($){
// PART I: Saving user details locally
$('#arlington-field-submit').on('click', function(){
// check if the user's browser has localStorage support
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
// store the full name in localStorage
var fullname = document.querySelector("input[name=arlington-name]");
localStorage.user_name = fullname.value;
// save the email in localStorage
var email = document.querySelector("input[name=arlington-email]");
$("input[name=fullname]").val(localStorage.getItem("server"));
localStorage.user_email = email.value;
}
});
// PART II: Pre-filling forms forms with locally saved values
if (typeof(Storage) !== "undefined") {
// check if the user has a name field stored
if (localStorage.user_name) {
name_field = document.querySelector("._form input[name=fullname]");
name_field.value = localStorage.user_name;
}
// check if the user has an email field stored
if (localStorage.user_email) {
email_field = document.querySelector("._form input[name=email]");
email_field.value = localStorage.user_email;
}
}
});
first form html:
<div id="arlington-element-form" class="arlington-element-form arlington-element" data-element="form">
<div id="arlington-form" class="arlington-form arlington-has-name-email arlington-has-buttons">
<div class="arlington-form-wrap"><input id="arlington-field-comments" name="arlington-comments" type="text" data-selectable="true" data-target="#builder-setting-comments_value" class="arlington-field-comments" placeholder="" value="" style="" autocomplete="off"><input id="arlington-field-name" name="arlington-name" type="text" data-selectable="true" data-target="#builder-setting-name_value" class="arlington-field-name" placeholder="Enter your name here..." value="">
<input id="arlington-field-email" name="arlington-email" type="email" data-selectable="true" data-target="#builder-setting-email_value" class="arlington-field-email" placeholder="Enter your email address here..." value="" >
<input id="arlington-field-submit" name="arlington-submit" type="submit" data-selectable="true" data-target="#builder-setting-submit_value" class="arlington-field-submit" value="JOIN NOW" >
</div>
<div class="arlington-yesno-wrap">
<button id="arlington-button-yes" type="button" name="arlington-yes" data-selectable="true" data-target="#builder-setting-yes_value" data-action="form" data-type="yes" class="arlington-button-yes arlington-button-yesno">Submit!</button>
</div></div></div>
second form html:
<form method="POST" action="xxxxxx" id="_form_8_" class="_form _form_8 _inline-form _dark" novalidate> <input type="hidden" name="u" value="8" /> <input type="hidden" name="f" value="8" /> <input type="hidden" name="s" /> <input type="hidden" name="c" value="0" /> <input type="hidden" name="m" value="0" /> <input type="hidden" name="act" value="sub" /> <input type="hidden" name="v" value="2" />
<div class="_form-content">
<div class="_form_element _x72304349 _full_width "> <label class="_form-label"> Full Name </label>
<div class="_field-wrapper"> <input type="text" name="fullname" placeholder="Type your name" /> </div>
</div>
<div class="_form_element _x10201592 _full_width "> <label class="_form-label"> Email* </label>
<div class="_field-wrapper"> <input type="text" name="email" placeholder="Type your email" required/> </div>
</div>
<div class="_form_element _x29901314 _full_width "> <label class="_form-label"> Phone </label>
<div class="_field-wrapper"> <input type="text" name="phone" placeholder="Type your phone number" /> </div>
</div>
<div class="_button-wrapper _full_width"> <button id="_form_8_submit" class="_submit" type="submit"> Submit </button> </div>
<div class="_clear-element"> </div>
</div>
</form>
Since the input which is being clicked is a submit button, chances are that the page is navigating before the JS within the click handler gets a chance to fire.
Try and replace
$('#arlington-field-submit').on('click', function(){
with:
$('#_form_8_').on('submit', function(event){
Then you can prevent the form from actually submitting so your JS can run:
$('#_form_8_').on('submit', function(event){
event.preventDefault();
// Do localStorage stuff
$(this).submit(); // submit the form normally after localStorage is saved
});
The way you look for elements is wrong, because you forgot quotes wrapping attribute values:
var fullname = document.querySelector("input[name=arlington-name]");
should be:
var fullname = document.querySelector('input[name="arlington-name"]');
And so on...
BTW I'm surprised you don't report an error like "An invalid or illegal string was specified".

How to check if all the radio buttons are selected or not?

Well I am trying to build a web page that has set of radio buttons. I am using jquery to check if all the radio buttons are checked or not. Here is the code:
<body>
<p class="Cal">Welcome,</p>
<hr />
<p class="Radio1">Answer the questions below. You will find the results after clicking 'Check my score'.</p>
<hr />
<form method="post">
<p class="Question">1. Do you sleep early at night? (Anywhere around 9-10pm)</p>
<p>
<label>
<span class="Radio">
<input type="radio" name="RadioGroup1" value="Yes" id="RadioGroup1_0" />
</span></label>
<span class="Radio"> Yes
<br />
<label>
<input type="radio" name="RadioGroup1" value="No" id="RadioGroup1_1" />
No
</label>
<br />
<label>
<input type="radio" name="RadioGroup1" value="Sometimes" id="RadioGroup1_2" />
Sometimes </label>
</span><br />
</p>
<p class="Question">2. Do you wake up early in morning?(Anywhere around 5-7am)</p>
<p>
<label>
<span class="Radio">
<input type="radio" name="RadioGroup2" value="Yes" id="RadioGroup2_0" />
Yes </span></label>
<span class="Radio"><br />
<label>
<input type="radio" name="RadioGroup2" value="No" id="RadioGroup2_1" />
No
</label>
<br />
<label>
<input type="radio" name="RadioGroup2" value="Sometimes" id="RadioGroup2_2" />
Sometimes
</label>
</span><br />
</p><input type="submit" value="Check my score" /></form></body>
Well there are 30 such questions. And my jquery code is as follows:
$(document).on('submit', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.Radio').each(function () {
// Question text
var Question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(Question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
else{
msg = "Done!";
alert(msg);
}
return validate;
});
Now I tried all ways possible to make this work. But even after I check radio button for each answer I keep on getting the popup saying "Please answer the following questions:" and then a blank list. I never get the message "Done!" even though answer for all the questions are checked.
Where is the fault?
You can use the HTML5 required attribute, which is better option.
You can also use JavaScript loop and retrieve the value from each radio group, using
$("input:radio[name=radiogroupX]:checked")

jQuery to Validate an Input Text Control based on Radio Selection

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!

Categories