If checkbox is checked add new input box [duplicate] - html

This question already has answers here:
Show box or input box on checked box
(2 answers)
Closed 8 years ago.
I have a form like this
<form >
<input type="text" placeholder="First Name" required id="fname" name="fname"/>
<input type="text" placeholder="Last Name" required id="lname" name="lname"/>
<input type="checkbox" placeholder="Maiden Name" id="Maiden Name" name="chkname"/>
<input type="hidden" placeholder="Maiden Name" id="mname" name="mname"/>
...
</form>
and if the checkbox is checked then the maiden name input box should be visible, can anyone help me with this.

In this instance, it's possible to do this without JavaScript, just use the :checked pseudo class:
EXAMPLE HERE
#mname {
display:none;
}
#maidenname:checked ~ #mname {
display:block;
}
Use either the general sibling combinator, ~, or the adjacent sibling combinator +, to change the display of the input element when the checkbox element is toggled. This of course assumes that the checkbox precedes the input element in the DOM.
If you would rather use JavaScript, you could use the following:
JS EXAMPLE HERE
var checkbox = document.getElementById('maidenname');
var input = document.getElementById('mname');
checkbox.addEventListener('click', function () {
if (input.style.display != 'block') {
input.style.display = 'block';
} else {
input.style.display = '';
}
});
Alternatively, if you would rather add an input element to the DOM (as your title implies), rather than changing the visibility of it, you could use something like this:
ALTERNATIVE JS EXAMPLE HERE
var checkbox = document.getElementById('maidenname');
checkbox.addEventListener('click', function () {
if (document.getElementById('mn')) {
document.getElementById('mn').remove();
} else {
var input = document.createElement("input");
input.id = 'mn';
input.type = 'text';
input.placeholder = 'Maiden Name';
document.body.appendChild(input);
}
});

you should not use maiden name input box as type="hidden". Use it as below:
<input type="text" style=" display:none" placeholder="Maiden Name" id="mname" name="mname"/>
Call function to toggle display on click of checkbox:
<input onchange="showHideControl();" type="checkbox" placeholder="Maiden Name" id="Maiden Name" name="chkname"/>
Toggle maiden name input box:
function showHideControl()
{
$('#mname').toggle();
}

You can do it using pure javascript, like so:
<form id=frmMain name=frmMain>
<input type="text" placeholder="First Name" required id="fname" name="fname"/>
<input type="text" placeholder="Last Name" required id="lname" name="lname"/>
<input type="checkbox" placeholder="Maiden Name" id="chkname" name="chkname" onclick=javascript:document.frmMain.mname.hidden=!document.frmMain.chkname.checked; />
<input type="input" hidden=true placeholder="Maiden Name" id="mname" name="mname"/>
...
</form>

Related

Add asterisk only if label text is available

I am trying to add an asterisk to a label text of an input, if the input filed is required. I used this answer and referred this answer and I can get the desired result using the following code
jQuery(function() {
jQuery("[required]").before(jQuery("<span>", {
class: "required"
}).html("*"));
});
However, I do not want the asterisk to be added for input fields where the label texts are not available.
Look at the following where a label text is not available;
<label>
<span class="required">*</span>
<input type="text" class="form-control" id="perm_city" name="perm_city" required="required" />
</label>
as opposed to the following where a label text is available
<label for="clientid">Client ID Number
<span class="required">*</span>
<input type="text" class="form-control" id="clientid" name="clientid" required="required" />
</label>
Both has the asterisk added before the input element by my jQuery script. But the desired output is as follows;
Can anyone help me achieve this? TIA
You can use .each loop to iterate through all required inputs then using .clone & .text() get the label texts ignoring all children it has . Then , if the length of text is greater then 0 append your span.
Demo Code :
jQuery(function() {
//loop through required input
jQuery("[required]").each(function() {
//get label and remove child only get text
var cloned = jQuery(this).closest("label").clone().children().remove().end().text().trim();
console.log("Length--" + cloned.length)
//check if txt length is > 0
if (cloned.length > 0) {
jQuery(this).before(jQuery("<span>", {
class: "required"
}).html("*"));
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="text" class="form-control" id="perm_city" name="perm_city" required="required" />
</label><br>
<label for="clientid">Client ID Number
<input type="text" class="form-control" id="clientid" name="clientid" required="required" />
</label><br>
<label for="clientid">Client ID Number1
<input type="text" class="form-control" id="clientid" name="clientid" required="required" />
</label><br>
<label for="clientid">
<input type="text" class="form-control" id="clientid" name="clientid" required="required" />
</label>
If this is how your labels are included, then you can clone each <label> element and remove its children, then check if any text remains. This is what I mean (I am not familiar with jQuery, so I will write in vanilla JS):
var labels = document.querySelectorAll("label");
for (var i = 0; i < labels.length; i++) {
var clonedLabel = labels[i].cloneNode(true);
var chldrn = clonedLabel.children.length;
for (var j = 0; j < chldrn; j++) {
clonedLabel.removeChild(clonedLabel.children[0]);
}
// Remove spaces
var innerHTML = clonedLabel.innerHTML.trim();
if (innerHTML != "") {
// Add the asterisk
var span = document.createElement("span");
span.className = "required";
span.innerHTML = "*";
labels[i].insertBefore(span,labels[i].children[0]);
}
}

HTML "readonly" input value can be edit when checked a check box

I have a input <input type="text" value="1" readonly id='aaa'/>.
I would like to give it a function when user check the box then can edit the value of id=aaa.
Sample:
<input type="text" value="1" readonly/> <input type="checkbox" /> Checked this if you want to edit the value.
Thank you.
Add an onchange event to the checkbox that changes to readOnly attribute of its previous sibling (the textfield)
<input type="text" value="1" readonly id="aaa" />
<input type="checkbox" onchange="getElementById('aaa').readOnly = !this.checked" />
Checked this if you want to edit the value.
You want to use JavaScript to change the readOnly property. Set it to the opposite of whether the checkbox is checked.
document.getElementById('checksome').addEventListener('click', function() {
var changeThis = document.getElementById('readsome');
changeThis.readOnly = !this.checked;
});
<input id="readsome" type="text" value="1" readonly>
<label><input id="checksome" type="checkbox"> Click this to edit</label>

Background color of required field

I am using the required attribute on certain fields in a form. When form is submitted, required fields that are not filled out get the standard red border around them. Is there a way to also change the background color of the required field that is not filled out after submitting? Here is just a sample textbox that I am using with the required attribute:
<input id="LastName" name="LastName" type="text" placeholder="Last Name" required/>
You can use CSS attribute selector like so:
input[required] {
background-color: red;
}
<input id="LastName" name="LastName" type="text" placeholder="Last Name"
required/>
This will select inputs with required attributes. Now, you can apply this with some simple JavaScript to achieve the desired effect:
var submit_button = document.getElementById("submit_button");
submit_button.addEventListener("click", function(e) {
var required = document.querySelectorAll("input[required]");
required.forEach(function(element) {
if(element.value.trim() == "") {
element.style.backgroundColor = "red";
} else {
element.style.backgroundColor = "white";
}
});
});
<input id="FirstName" name="FirstName" type="text" placeholder="First Name" required/>
<input id="LastName" name="LastName" type="text" placeholder="Last Name" required/>
<input id="submit_button" type="submit">
What this does is add an event listener when the submit button is clicked. When it is, it uses querySelectorAll to get all the inputs that match the CSS attribute selector, input[required]. Next, it does a for-each loop over the returned list of elements. Finally, it checks each inputs value, trimmed, to makes sure there's some content in there (spaces don't count). If there's nothing in the input, it sets the background color to red.
Notes:
You can tweak it as you like, make sure to cancel whatever event you are handling if the inputs are invalid, and you can add classes for styles instead of using element.style.<style>.
You can change it using css as mentioned in some comments above, if it doesn't work then check whether parent background-color attribute is set, in that case you can use !important tag to enforce for the child.
Hello you can try this by basic Css
:required {
background: red;
}
Or using jQuery easily it will work dynamically On button click the background color will be red hope it helps.
the html code
<input id="LastName" name="LastName" type="text" placeholder="Last Name"
required/>
<input id="sub" type="button">
and the jquery code
<script>
$('#sub').click(function(){
$('#LastName').each(function() {
if($(this).val() == '') {
$(this).css('background-color' , '#FF0000');
$(this).attr("placeholder", "Required");
}
});
});
</script>
But if you want to do this for an entire form then it will be something like below
<script>
$('#sub').click(function(e){ //submit button name
e.preventDefault()
$('.required').each(function() { //a constant class for evert input item
if($(this).val() == '') {
$(this).css('background-color' , '#FF0000');
$(this).attr("placeholder", "Required");
}
});
});
</sctript>
see the below fiddle
required Fiddle
must add inside head jQuery Library
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
</head>
input[type="text"],lastname {
background-color : red;
}
body input:focus:required:invalid,
body textarea:focus:required:invalid {
color: green;
}

Storing checkbox tag values to an Javascript Object and String value via JSON

I'm probably making some rookie mistakes, but my brain is drained trying to figure out where I went wrong. I have an HTML form, and I need to store JUST the values of the checked selections in an script object (if it's deselected, it should be removed from the object), as well as convert the object into a string. Problem is, I haven't ever had to mix checkboxes with Javascript, and I'm completely lost. When I debug, it completely ignores the function. Any help would be greatly appreciated.
HTML for the form:
<form method="post" action="http://webdevbasics.net/scripts/demo.php">
<div id="errorText"></div>
<fieldset id="faq">
<label for="uname">Name:</label>
<input type="text" name="uname" id="uname" required="required">
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" required="required">
<label for="nature" required="required">Nature of your question:</label>
<input type="checkbox" name="nature" id="A" value="A">Option A
<input type="checkbox" name="nature" id="B" value="B">Option B
<input type="checkbox" name="nature" id="C" value="C">Option C</br>
<input type="checkbox" name="nature" id="D" value="D">Option D
<input type="checkbox" name="nature" id="other" value="other">Other
<label for="question">Question(s):</label>
<textarea name="question" id="question" rows="10" cols="50" required="required">
</textarea>
</fieldset><p>
<input id="submit" type="submit" value="Submit">
</form><p>
And here's the Javascript:
"use strict";
var natureObject = new Object();
var natureSubmission = "";
function checkboxObject() {
var checkBoxes = document.getElementsByClassName("box");
natureObject = {};
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
natureObject[fields[i].name] = checkBoxes[i].value;
}
}
}
function createString() {
natureSubmission = JSON.stringify(natureObject);
}
/* create event listeners */
function createEventListeners() {
var box = document.getElementsByClassName("box");
if (box.addEventListener) {
box.addEventListener("change", checkboxObject, false);
} else if (box.attachEvent) {
box.attachEvent("onchange", checkboxObject);
}
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
} else if (window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
"nature" is not tagName, tagName is "input".
I suggest to add a class for all checkboxes and use getElementsByClassName(), then iterate over them with a for loop.
As a side note, I am unsure whether you can have multiple checkboxes with the same name in a form submission though.

Hide label for input without attribute "required" (float label)

I have this code:
<span class="field">
<input type="text" id="first-name" placeholder="First Name" required />
<label for="first-name">First Name</label>
</span>
<span class="field">
<input type="text" id="last-name" placeholder="Last Name" />
<label for="last-name">Last Name</label>
</span>
Label for the second input ("Last Name") is visible from the beginning and not only on focus like the "First Name" label. The difference between two inputs is only in attribute "required" which I don't need for the "Last Name" field.
How to make label for input without attribute "required" hidden? I need it to be shown only on focus with the transition effect. The same like this work for "First Name" field.
http://jsfiddle.net/dmitriy_kalmykov/68jmbquy
You could use the adjacent sibling selector. Add the following code to your CSS file.
input[required] + label {
display: none;
}
What about using required for the last-name field too, but overwriting the required attribute for the last-name input by javascript while submiting the form.
document.getElementById("last-name").required = false;
I know this question was asked 9 month ago, but this can help somebody in future.
I guess you can't submit the form because all fields with float labels should be with the required attribute.If you leave a field empty, the form won't submit. If you remove the attribute, the label is visible and you can submit the form, but the idea of floating labels is ruined.
If I am correct, then try this code:
$( document ).ready(function() {
$('#sub-btn').click(function validateForm() {
var isValid = true;
$('.field').each(function() {
if ( $(this).val() === '' )
$(this).removeAttr("required");
});
return isValid;
});
});
It works for me. You should set the submit button with id="sub-btn" so when you click it, it will clean the required properties.