How to give the user the ability to add another choice data? - javascript

I have a select dropdown menu, The user selects one of the options then the related form inputs are shown.
Here is the html:
<select id="relative" name="relative">
<option>Select relative</option>
<option value="father">father</option>
<option value="mother">mother</option>
<option value="brother">brother</option>
</select>
<div id="relative_sections">
<div id="father">
<input type="text" id="father_name" name="father_name" placeholder="Name" />
<input type="email" id="father_email" name="father_email" placeholder="Email" />
<input type="number" id="father_phone" name="father_phone" placeholder="phone" />
</div>
<div id="mother">
<input type="text" id="mother_name" name="mother_name" placeholder="Name" />
<input type="email" id="mother_email" name="mother_email" placeholder="Email" />
<input type="number" id="mother_phone" name="mother_phone" placeholder="phone" />
</div>
<div id="brother">
<input type="text" id="brother_name" name="brother_name" placeholder="Name" />
<input type="email" id="brother_email" name="brother_email" placeholder="Email" />
<input type="number" id="brother_phone" name="brother_phone" placeholder="phone" />
</div>
</div>
CSS code for hiding all the sections:
#mother,
#father,
#brother{
display:none;
}
Javascript code to show/hide sections on changing selected option:
<script type="text/javascript">
function hideAllChildrenButOne(parentId, toRevealId) {
var children = document.getElementById(parentId).children;
for (var i=0; i<children.length; i++) children[i].style.display="none";
document.getElementById(toRevealId).style.display="block";
}
document.getElementById('relative').addEventListener('change', function(){
if (this.value !== '') {
hideAllChildrenButOne('relative_sections', this.value);
}else{
var children = document.getElementById('relative_sections').children;
for (var i=0; i<children.length; i++) children[i].style.display="none";
}
});
</script>
Here is a live fiddle to see what is going on: http://jsfiddle.net/38db59cx
Then I validate the inputs depending on the selected value:
if($_POST['relative'] == 'father'){
//Validate the inputs
}elseif($_POST['relative'] == 'mother'){
//Validate the inputs
}elseif($_POST['relative'] == 'brother'){
//Validate the inputs
}
What I want do is to give the user the ability to select more than one option like ('father' and 'mother') or even all of them then I validate all, But he must at least fill one option data.
How to do this so the user at least select one option, fills the inputs for this option and still could select another option, So that I can validate what he selects?
Most important thing is that the user should select at least one and fill the related ata and can also select more than one.

You could change your select box to either a multiple select or checkboxes. If using checkboxes you would set the name to name='relative[].
Checkboxes:
<label>father<input type="checkbox" name="relative[]" value="father"></label>
<label>mother<input type="checkbox" name="relative[]" value="mother"></label>
<label>brother<input type="checkbox" name="relative[]" value="brother"></label>
MultiSelect
<select name="relative" multiple>
Then in php you can read the data like this:
// create a container to hold the validated results
$aRelative = array();
// if post data exists proceed to check the resutls
if(isset($_POST['relative'])){
// loop over each post value
foreach($_POST['relative'] as $iPos => $a){
// do some validation on the result
if($a != ""){
$aRelative[] &= $a;
}
}
}
if(!empty($aRelative)){
//do whatever with the data
}

So to my understanding, you want user to select multiple option and want to validate them as well. So here is the piece of code which I am sharing. You need to use attribute 'multiple' in your select tag for multiple options to get selected. Here it is:
Click here and check the code, you want to do something similar
In the javascript, you can do something this and add validation for the options.
$('#RNA').submit(function(){
var options = $('#sampleMut > option:selected');
if(options.length == 0){
alert('no value selected');
return false;
}
});
Note: To select more than one option you need to do => press command/CTRL + click options.
Hope it helps a little!

Related

Output Contents of Input in div

I am creating a contact form that creates something like a cart view depending on the inputs.
I managed to get all the checkboxes to output when they are checked; I am having trouble getting the same to work with text and number inputs. So input type text, number and textarea.
<input id="form_name" type="text" name="name" class="form-control"
placeholder="Please enter your firstname *" required="required"
data-error="Pflichtfeld" data-validate="true">
<input type="number" id="age" name="age" min="16" max="99"
class="form-control" required="required"
data-error="Pflichtfeld" data-validate="true">
<div id="descript11" style="display:none;">Vorname:
<b id="vorname"></b>
</div>
<div id="descript12" style="display:none;">Alter:
<b id="alter"></b>
</div>
So I tried the method with $(document).change() but that did not work. I want to grab the contents of the input or textarea and output it to the div with the corresponding id. So "age" should output to "alter" and so on. I'm not sure how to achieve this and w3schools or other sites don't offer an answer.
You can do this by adding an input event listener to your input text boxes. In the example below, I loop through all your input text boxes (as I gave them a class of text-input) using a forEach loop. You can then grab the text from the textbox using this.value and place it into its associated div. To help with this I created a mapping object which is used to map the id of the input to the id of where the text should be placed into.
See example below:
const input_map = {
form_name: "vorname",
age: "alter"
}
document.querySelectorAll(".text-input").forEach(elem => {
elem.addEventListener('input', function() {
const textbox_value = this.value; // get text from input bpx
const target = input_map[this.id]; // get location (ie: the id) of where the text should be placed
document.getElementById(target).innerText = textbox_value; // place the text in that location
});
});
<input id="form_name" type="text" name="name" class="form-control text-input" placeholder="Please enter your firstname *" required="required" data-error="Pflichtfeld" data-validate="true">
<input type="number" id="age" name="age" min="16" max="99" class="form-control text-input" required="required" data-error="Pflichtfeld" data-validate="true">
<div id="descript11">Vorname:<b id="vorname"></b></div>
<div id="descript12">Alter: <b id="alter"></b></div>
Note: In the example above I removed the style="display: none;" from your divs so that you can see the output
You can do it like this:
$('input').on('input',function(){
let text = $(this).val();
let id = $(this).attr('id');
$('div.'+id).text(text)
});
This snippet checks changes on inputs and sets their value to the div with class that matches each input's id .

Input field value with visibility hidden not getting posted

I have a select box with options of numbers in it.Whenever user selects an option i am displaying input box through jquery depending on the number selected.So for this the input box are initially hidden. Now the problem is that when i try to post the value of those input box, they are not getting posted.
Here is html code-
<form action="data.php" method="POST">
Select the number of company:
<select name="num_of_comp" id="num_of_comp">
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="div1" style="visibility:hidden;">
<label for="dbname">database name:</label>
<input type="text" name="db1" id="db1" />
<input type="submit" name="submit" id="submit" />
</div>
<div id="div2" style="visibility:hidden;">
<label for="dbname">database name:</label>
<input type="text" name="db1" placeholder="db1 name"/>
<input type="text" name="db2" placeholder="db2 name"/>
<input type="submit" name="submit" id="submit" />
</div>
Here is the script that dynamically displays the input box -
$('#num_of_comp').on('change',function(){
if( $(this).val()==="1"){
$("#div1").css("visibility", "visible");
$("#div2,").css("visibility", "hidden");
}
else if( $(this).val()==="2"){
$("#div2").css("visibility", "visible");
$("#div1").css("visibility", "hidden");
}
Here is php code-
$i = $_POST['num_of_comp'];
if($i == '1'){
$db1 = $_POST['db1'];
echo $db1;
Here I am not getting the value of db1.
Thanks in advance.
You can not set same id to multiple fields, id should be unique for all fields.
so set different ids to all fields in form
Even the name of the all input fields should be unique here.
You have two inputs with name db1. The second value (input without id) overwrites the first one (input with id="db1").
This is your issue
You have use same id for two input fields that is wrong every id in the page should be unique otherwise you can't get the actual value of your expecting field, and use proper naming for those id then you wan't miss those issue and code will be clear also use different name for name attribute
<input type="text" name="db1" id="database1" />
<input type="submit" name="submit" id="submit" />
<div id="div2" style="visibility:hidden;">
<label for="dbname">database name:</label>
<input type="text" name="db2" id="database2" placeholder="db1 name"/>
</div>

jquery radio button each -not working

i am trying to loop through the radio buttons by name with 'each' function..the each function is not working and it is applying the logic only once and it is not looping for the next time..
My use case is, when user selects value from the select dropdown, needs to enable both the radio buttons and if the user deselects the dropdown- needs to disable back..
Here in my case, each function is looping only once and after that it is getting exit from it..Need help in figuring disable/enable based on dropdown selection..
html code:-
<div class="uriDiv input-group">
<select class="common authSelect form-control" name="authType" id="authType">
<option value="">
<spring:message code="newPolicy.selectAuthType"></spring:message>
</option>
<option value="DB">DB</option>
<option value="LDAP">LDAP</option>
</select>
</div>
<td>
<div class="auth-permission-rd">
<div class="uriDiv radio radio-left">
<label>
<input type="radio" class="common anyuser" value="anyUser" name="authPermission" id="authPermission" disabled="disabled">Any User
</label>
</div>
<div class="uriDiv radio radio-input">
<label>
<input type="radio" class="common groupuser" value="groupUser" name="authPermission" id="authPermission" disabled="disabled">
<input type="text" name="authPermissionValue" disabled="disabled" class="common form-control-placeHolder" id="authPermissionValue" placeholder="Enter custom Permissions - Comma separated" />
</label>
</div>
</div>
jquery:
$("#authType").change(function(){
if($(this).val()){
$("input:radio[name='authPermission']").each(function(){
$("#authPermission").prop('disabled',false);
$("#authPermission").prop('checked',false);
});
}
else{
$("#authPermission").each(function(){
$("#authPermission").prop('disabled',true);
$("#authPermission").prop('checked',false);
});
}
});
You cannot have more than one element with the same ID. So, I would change your code by removing the id attribute and putting a new value for the class attribute, then fetch the object using jquery class selector.
<div class="uriDiv input-group">
<select class="common authSelect form-control" name="authType" id="authType">
<option value="">
<spring:message code="newPolicy.selectAuthType"></spring:message>
</option>
<option value="DB">DB</option>
<option value="LDAP">LDAP</option>
</select>
</div>
<td>
<div class="auth-permission-rd">
<div class="uriDiv radio radio-left">
<label>
<input type="radio" class="common anyuser authPermission" value="anyUser" name="authPermission" disabled="disabled">Any User
</label>
</div>
<div class="uriDiv radio radio-input">
<label>
<input type="radio" class="common groupuser authPermission" value="groupUser" name="authPermission" disabled="disabled">
<input type="text" name="authPermissionValue" disabled="disabled" class="common form-control-placeHolder authPermissionValue" placeholder="Enter custom Permissions - Comma separated" />
</label>
</div>
</div>
And jQuery code :
$("#authType").change(function(){
if($(this).val()){
$("input:radio[name='authPermission']").each(function(elemId, elem){
$(elem).prop('disabled',false);
$(elem).prop('checked',false);
});
}
else{
$(".authPermission").each(function(elemId, elem){
$(elem).prop('disabled',true);
$(elem).prop('checked',false);
});
}
});
But, if we take a better look at your code, I do not understand why you want to use "each". You can achieve the same thing without it :
// Following code :
$(".authPermission").each(function(elemId, elem){
$(elem).prop('disabled',true);
$(elem).prop('checked',false);
});
// Does the same thing as this one :
$(".authPermission").prop('disabled', true).prop('checked', false);
I refactored your code. Also enables the input field when the appropriate radio is clicked. This sould work:
function updateUI() {
var select = $("#authType");
var value = select.val();
var should_appear = (value.length == 0);
$("input:radio[name='authPermission']").attr('disabled',should_appear);
}
//binding...
$("input:radio").on("click", function() {
var should_display_textbox = !($(this).val() === "groupUser");
console.log(should_display_textbox);
$("input:text[name='authPermissionValue']").attr('disabled', should_display_textbox);
});
$("#authType").change(function(){
updateUI();
});
$(document).ready(function() {
updateUI(); //update also when page load
});
Something like this maybe?
$("#authType").change(function(){
var disabled = !$(this).val() ? true : false;
$("input:radio[name='authPermission']").each(function(){
$(this).prop('disabled', disabled );
$(this).prop('checked',false);
});
});

Can't get JavaScript SSN Form Validation to work

I am new to JS and trying to get it so when someone enters a SSN number in a field, it gives them an alert telling them to NOT put a SSN number in there.
HTML:
<form name="card" action="#">
<input type="text" name="field" class="name social" size="60" placeholder="First and Last Name">
<input type="text" name="field" class="phone social" size="60" placeholder="Phone Number">
<input type="text" name="field" class="email social" size="60" placeholder="Email(name#example.com)">
<select class="select">
<option value="My card has not yet arrived">My card has not yet arrived
<option value="Direct Deposit">Direct Deposit
<option value="Suggest a Card">Suggest a Card
<option value="Issues with CARD.com">Issues with CARD.com
<option value="Other">Other
</select>
<textarea name="field" class="text social " cols="60" rows="5" placeholder="How can we help you?"></textarea>
<input type"submit" name="submit" class="subBtn" value="Submit" onclick="warnCC(document.card.field)">Submit</input>
</form>
JS:
<script>
function warnCC()
{
var ssn = document.getElementsByTagName("input");
// document.getElementsByClassName("social");
var pattern = /^[0-9]{3}\-?[0-9]{2}\-?[0-9]{4}$/;
if (ssn.value.match(pattern))
{
return true;
alert("Please Do Not Enter SSN Info Into This Form");
}
else
{
return false;
alert("yay!")
}
}
</script>
Any help on where I cam going wrong would be very helpful. I'd also prefer it was done on a "onfocusout" if anyone can give me advice on that.
getElementsByTagName and getElementsByClassName both return a list of elements. That list doesn't have a value property. Each of the items on the list has a value property, but not the list.
You'll want to loop through the list of inputs and handle each of them as appropriate, e.g.:
var list = /*...get the list using either method you have in your code...*/;
var index, input;
for (index = 0; index < list.length; ++index) {
input = list[index];
// input.value will be the value of this particular input
}
Side note: querySelectorAll has better support than getElementsByClassName (IE8 has it, for instance, but not getElementsByClassName), so if you want to get a list using a class, you're best off with:
var list = document.querySelectorAll(".the-class-here");
You should also do the alert() before returning from the function ... if you want the alert() dialog to be displayed.
I tweaked your function. You can see it inaction here: http://jsfiddle.net/tBqP2
function warnCC() {
var formElements = document.getElementsByTagName("input");
for (var k in formElements) {
// document.getElementsByClassName("social");
var pattern = /^[0-9]{3}\-?[0-9]{2}\-?[0-9]{4}$/;
if (formElements[k].value.match(pattern)) {
alert("Please Do Not Enter SSN Info Into This Form");
return false;
}
}
return true;
}

binding events triggered by multiple input fields

what are the best practices to binding events triggered by multiple input fields which are dependent on each other in jquery?
For eg: lets take a search engine which searches for students based on what is entered and selected in the fields below.
1. text boxes
2. select lists
3. select boxes
4. option buttons
Without a button which will trigger these events, what is the best way to achieving the following:
Displaying search result as soon as user enters or selects values in one of the input fields and refines the search as users enters or selects values in other fields options.
Displaying search result only after each fields has a valid value.
Any input would be appretiated.
I've put this together this jsFiddle http://jsfiddle.net/VJwpv/1/.
If you are looking at doing validation with JavaScript then I'd recommend you look into this jQuery Validation plugin
HTML
<div id="searchForm">
<input id="textBox" class="searchField" type="text" />
<select id="dropDown" class="searchField">
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
</select>
<input id="checkbox1Value" type="checkbox" name="checkbox" value="Checkbox1" />Checkbox1
<input id="checkbox2Value" type="checkbox" name="checkbox" value="Checkbox2" />Checkbox2
<input type="radio" name="radio" value="Radio1" /> Radio1
<input type="radio" name="radio" value="Radio2" /> Radio2
</div>
<div id="results"></div>
JavaScript
function validateForm() {
// if valid
return true;
// else return false
}
function performSearch() {
var textBoxValue = $("#textBox").val();
var dropDownValue = $("#dropDown").val();
var checkbox1Value = $("#checkbox1Value").is(":checked");
var checkbox2Value = $("#checkbox2Value").is(":checked");
var radioValue = $("input:radio[name=radio]:checked").val();
// What you'd actually do here is an AJAX call to get the search results
// and pass all the values defined above in the request
$("#results").html("Textbox: " + textBoxValue + ". Dropdown: " + dropDownValue + ". Checkbox1: " + checkbox1Value + ". Checkbox2: " + checkbox2Value + ". Radio: " + radioValue);
}
function onChange() {
if (validateForm()) {
performSearch();
}
}
$(document).ready(function() {
$("#searchForm input, #searchForm select").change(function() {
onChange();
});
});​
Just give them all a common class name, and bind the change event using a class selector:
HTML:
<input type="text" class="search-field" />
<input type="text" class="search-field" />
<select class="search-field" ><option>1</option><option>2</option></select>
<input type="radio" class="search-field" />
JS:
$('.search-field').change(function() {
// validate all search field values
// display search results based on values
// if search results already shown, filter based on $(this).val()
});
If you have many of these fields, rather than having a handler be bound to each one (as the above code accomplishes), you would get better performance by using a delegated event handler:
HTML:
<div id='parent'>
<input type="text" class="search-field" />
<input type="text" class="search-field" />
<select class="search-field" ><option>1</option><option>2</option></select>
<input type="radio" class="search-field" />
</div>
JS:
$('#parent').on('change', '.search-field', function() {
// validate all search field values
// display search results based on values
// if search results already shown, filter based on $(this).val()
});

Categories

Resources