is that possible to populate attributes name, value, type from :input or something like jQuery serialize for all kinds of input, and combine the value if there is have multiple name like checkbox and radio choices
the concept like this :
$(this).attr('name');
$(this).attr('type');
$(this).attr('value'); // <--- combine this value when the type is checkbox or radio
i try to populate the attributes using each function :
it work but i still don't know how to combine type
$('.submit').click(function(){
var tipe = {}
var form = {}
$('input[type=text], textarea', '.register').each(function(){
const name = $(this).attr('name');
const value = $(this).val();
const type = $(this).attr('type');
form[name] = value;
tipe[name] = type;
});
$('input[type=checkbox], input[type=radio]', '.register').each(function(){
const name = $(this).attr('name');
const value = $(this).val();
const type = $(this).attr('type');
if(form[name] === undefined) {
form[name] = [value];
tipe[name] = [type];
} else {
form[name].push(value);
}
});
console.log(form);
//console.log(tipe);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="register">
<input type="text" name="full_name">
<textarea name="address"></textarea>
<input type="radio" name="sex" value="male">
<input type="radio" name="sex" value="female">
<input type="checkbox" name="hobies" value="foodball">
<input type="checkbox" name="hobies" value="basketball">
</div>
<input type="button" class="submit" value="Submit">
you can use below logic where you can create one map to store value of each input and append values if input type is of type radio or checkbox
$('.submit').click(function(e){
var formValues = {};
$('.register :input').each(function(){
var name = $(this).attr('name');
var type = $(this).attr('type');
var value = $(this).val();
var inputElement = {};
var valid = true;
if(type == 'radio' || type == 'checkbox') {
valid = $(this).is(':checked');
if(valid) {
if(formValues[name]) {
inputElement = formValues[name];
var preVal = inputElement['value'];
value = preVal + ',' + value;
}
}
}
if(valid) {
inputElement['name'] = name;
inputElement['type'] = type;
inputElement['value'] = value;
formValues[name] = inputElement;
}
});
console.log(formValues);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="register">
<input type="text" name="full_name">
<textarea name="address"></textarea>
<input type="radio" name="sex" value="male">
<input type="radio" name="sex" value="female">
<input type="checkbox" name="hobies" value="foodball">
<input type="checkbox" name="hobies" value="basketball">
</div>
<input type="button" class="submit" value="Submit">
Related
I was making a password generator while learning javascript. Is there a way to call the checked radio button using a value or do I switch to getElementbyId while calling.
My HTML body-
<div class="container">
<p>Please select the type of Password you want to generate:</p>
<form id="new-form">
<input type="radio" id="wp" name="radio" class="redio" value="0" />
<label for="wp">Weak Password</label><br />
<input type="radio" id="sp" name="radio" class="redio" value="1" />
<label for="sp">Strong Password</label><br />
<input type="radio" id="ssp" name="radio" class="redio" value="2" />
<label for="ssp">Super Strong Password</label>
<br />
<input type="submit" id="btn" value="Generate Password" />
</form>
<div id="display" type="text" readonly="true"></div>
</div>
My javascript-
class password{
constructor(){
this.ucl="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
this.lcl="abcdefghijklmnopqrstuvwxyz"
this.num="1234567890"
this.spc = "!##$%^&*()"
}
weakpassword(){
let arr = [this.ucl, this.lcl]
let pass = ""
for(let i=0;i<8;i++){
let random1= Math.floor(Math.random()*arr.length)
let random2= Math.floor(Math.random()*arr[random1].length)
pass= pass + arr[random1][random2]
}
return pass
}
strongpassword(){
let arr = [this.ucl, this.lcl, this.num]
let pass = ""
for(let i=0;i<14;i++){
let random1= Math.floor(Math.random()*arr.length)
let random2= Math.floor(Math.random()*arr[random1].length)
pass= pass + arr[random1][random2]
}
return pass
}
superstrongpassword(){
let arr = [this.ucl, this.lcl, this.num, this.spc]
let pass = ""
for(let i=0;i<20;i++){
let random1= Math.floor(Math.random()*arr.length)
let random2= Math.floor(Math.random()*arr[random1].length)
pass= pass + arr[random1][random2]
}
return pass
}
}
let display = document.getElementById("display");
let btn = document.getElementById("btn");
let radio = document.getElementsByClassName("redio");
let a = new password()
btn.addEventListener("click",()=>{
let b;
// if(document.getElementById('wp').checked){
// b= a.weakpassword()
// }
if(radio[0].checked){
b= a.weakpassword()
}
else if(radio[1].checked){
b= a.strongpassword()
}
else if(radio[2].checked){
b= a.superstrongpassword()
}
display.value= b
})
Here, I am getting an error-
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
I'm trying to call the checked radio option value but getting an error 'Cannot read properties of null'.
Hello I am inquiring assistance on how to grab the value of a Element corresponding to its element using plain Javascript.
My HTML:
<label id ="label1" for = "vanilla">Vanilla
<input type ="checkbox" id = "vanilla" name = "icecream">
</label><br>
<label id = "label2" for = "chocolate"> chocolate
<input type = "checkbox" id = "chocolate" name = "icecream">
</label><br>
<label id = "label3" for = "coffee"> Coffee
<input type = "checkbox" id = "coffee" name = "icecream">
</label>
My Javascript, Which currently returns either 'Null' or a BlankSpace:
var IceCreamBox = document.getElementsByName("icecream");
var RootBeerBox = document.getElementsByName("rootbeers");
var t;
var j = [];
for( var i = 0; i < IceCreamBox.length; i++)
{
if(IceCreamBox[i].checked == true)
{
j[i] = IceCreamBox[i].nodeValue;
}
You could use filter to keep only the checked ones, map and document.querySelector to find their corresponding label:
// Convert the HTMLCollection to an Array to be able to use forEach, filter, map
var IceCreamBox = [...document.getElementsByName("icecream")];
IceCreamBox.forEach(cb => cb.addEventListener('click', listCheckedOptions));
function listCheckedOptions() {
var j = IceCreamBox
// Filter to keep only the checked ones
.filter(cb => cb.checked)
// Map them to their label text
.map(cb => document.querySelector(`label[for="${cb.id}"]`).textContent.trim());
console.log(j);
}
<label for="vanilla">Vanilla
<input type ="checkbox" id="vanilla" name="icecream">
</label><br>
<label for="chocolate">Chocolate
<input type="checkbox" id="chocolate" name="icecream">
</label><br>
<label for="coffee">Coffee
<input type="checkbox" id="coffee" name="icecream">
</label>
I've got an HTML form that consists of a series of units like this:
<input name="categoryColor[]" />
<input name="categoryName[]" />
Using this jQuery code, I can capture this data and return it in an object like this:
{categoryColor: [array of values],
categoryName: [array of values]}
Here's an example of the code in action:
const getFormDataFromElem = function($elem, options) {
options = options || {};
const vis = options.onlyVisible ? ":visible" : "";
const formInputs = $elem.find(`:input${vis}, [contenteditable=true]${vis}`);
const data = {};
formInputs.each(function() {
const $this = $(this)
const type = $this.attr('type');
const val = type === "checkbox" ? (this.checked ? "1" : "0") :
($this.is('[contenteditable=true]') ? $this.text() : this.value);
const name0 = $this.attr('name');
const doArray = name0 && name0.slice(-2) === "[]";
const name = doArray ? name0.slice(0, -2) : name0;
if (!name || (!options.saveEmpty && !doArray && val === "")) {
return;
}
if (doArray) {
if (data.hasOwnProperty(name)) {
data[name].push(val);
return
}
data[name] = [val];
return;
}
data[name] = val;
});
return data;
};
const data = getFormDataFromElem($('.input'));
$('.output').text(JSON.stringify(data, null, 2));
.output {
font-family: monospace;
white-space: pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Input</h2>
<div class="input">
<input name="categoryName[]" value="phase1"/>
<input name="categoryColor[]" value="red"/>
<input name="categoryName[]" value="phase2"/>
<input name="categoryColor[]" value="green"/>
<input name="categoryName[]" value="phase3"/>
<input name="categoryColor[]" value="blue"/>
</div>
<h2>Output</h2>
<div class="output"></div>
BUT I'd like to be able to write the HTML form units like this
<input name="categories[].color" />
<input name="categories[].name" />
since I really need this data in this form:
{categories: [array of objects],
}
where the objects have the form {name: '<name of category>', color: '<color string>'}.
How would I rewrite my general-purpose form-capturing routine to produce values that are arbitrary arrays and objects?
Following assumes you are able to group each set of inputs that make up one object. Then rather than having to parse names use data attributes on the group container for the main object property name.
Still a bit unclear if this is what you are after but can also modify to suit more specific needs. I realize the names are not unique and not sure if that is an issue or not
const data = {};
$('.input').each(function(i){
const $cont = $(this),
{struct, prop} = $cont.data(),
inputs = $cont.find('input').toArray();
if(struct === 'obj'){
data[prop] = data[prop] || [];
const obj = inputs.reduce((a,c)=>({...a, [c.name]:c.value}),{})
data[prop].push(obj);
}
})
console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input" data-struct="obj" data-prop="otherCat">
<input name="name" value="phase1" />
<input name="color" value="red" />
</div>
<div class="input" data-struct="obj" data-prop="categories">
<input name="name" value="phase2" />
<input name="color" value="green" />
</div>
<div class="input" data-struct="obj" data-prop="categories">
<input name="name" value="phase3" />
<input name="color" value="blue" />
</div>
I have 15 or so individual checkboxes each without id or class, the problem is I would like for them all to retain their individual checked or unchecked status (using local storage) either on form submit or page refresh
<form name="searchform" id="form1" method="get" action="/ztest.php">
<input type="checkbox" name="opt17" value="Yes"/>
<input type="checkbox" name="opt18" value="Yes"/>
<input type="checkbox" name="opt19" value="Yes"/>
etc...
</form>
My question is, is this possible in Javascript to save them in local storage without having to assign a class or id to each checkbox?
If possible, a working fiddle would be gratefully appreciated
Jason
Let's assume our checkboxes are blind
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
Now we need to find out which element was clicked, for this we can get the index of the element which is clicked.
const clickedIndex = [...event.target.parentElement.children].indexOf(event.target);
this line will gives you the index of clicked element which you can save in your localstorage
localStorage.setItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
and also you can check whenever your page load that which index is saved in your localstorage.
const inputs = document.querySelectorAll("input");
console.log(inputs);
if (localStorage.length > 0) {
for (let key in localStorage) {
if (!isNaN(localStorage[key]))
inputs[localStorage[key]].checked = true;
}
}
hence the complete code
<body>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
</body>
<script>
const inputs = document.querySelectorAll("input");
console.log(inputs);
if (localStorage.length > 0) {
for (let key in localStorage) {
if (!isNaN(localStorage[key]))
inputs[localStorage[key]].checked = true;
}
}
function clickThis(event) {
console.log(event.target);
const el = event.target;
const clickedIndex = [...el.parentElement.children].indexOf(el);
if (event.target.checked) {
// adding click value to local storage
localStorage.setItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
} else {
// deleting unchecked value from localstorage
localStorage.removeItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
}
}
</script>
#happy_coding
REPL link
https://repl.it/repls/SlateblueCorruptScale
This is the second way to achieve the above problem.
Let's assume you don't want to define that onclick on each of your tag.
all you need to do is listen the event. shhhhh
document.addEventListener("click", function(event){
console.log(event.target);
});
so you are able to listen the event right ?. Now where in your body you click will be heard by this. But as per your scenario you need to listen only when the input type checkbox clicked.
so we will add a condition
if (event.target.type === "checkbox") {
// this is checkbox bro
}
and rest of strategy will be same like get the index store it into local-storage and add the checkbox value true while loading.
so here is complete code
<body>
<input type = "checkbox"/>
<input type = "checkbox" />
<input type = "checkbox"/>
<input type = "checkbox"/>
<input type = "checkbox"/>
<input type = "checkbox"/>
<input type = "checkbox"/>
<input type = "checkbox"/>
</body>
<script>
const inputs = document.querySelectorAll("input");
console.log(inputs);
if (localStorage.length > 0) {
for (let key in localStorage) {
if (!isNaN(localStorage[key]))
inputs[localStorage[key]].checked = true;
}
}
document.addEventListener("click", function(event){
console.log(event.target);
if (event.target.type === "checkbox") {
const el = event.target;
const clickedIndex = [...el.parentElement.children].indexOf(el);
if (event.target.checked) {
// adding click value to local storage
localStorage.setItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
} else {
// deleting unchecked value from localstorage
localStorage.removeItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
}
}
});
</script>
REPLLINK
i am geting undefined for ans . why? what is wrong?
function submitAnswer()
{
var myForm = document.getElementById('quiz');
var ansVal = myForm.ans.value;
var qnoVal = myForm.qno.value;
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
<form nam="quiz" id="quiz" >
Yes:
<input type="radio" id="ans" name="ans" value="1" />
<br />No:
<input type="radio" id="ans" name="ans" value="0" />
<input id="qno" type="text" name="qno " value="qqq" />
<input type="button" value="" onClick="submitAnswer(); " />
</form>
Using theForm.inputElement is not standard and can't be guaranteed to work. Instead, you should use document.getElementById, or some other DOM mechanism, to find the input element you want. theForm.elements[name] also works.
You'll also need to fix your element IDs before you can do that - you have two <input type="radio" /> elements with an ID "ans", which is incorrect. IDs must be unique:
<input type="radio" id="ans1" name="ans" value="1" />
<input type="radio" id="ans2" name="ans" value="0" />
<script type="text/javascript">
var ans1 = document.getElementById('ans1');
var ans1value = ans1.value;
</script>
Or, get the radio button group as a single element using elements:
<script type="text/javascript">
var theForm = document.getElementById('quiz');
var ansValue = theForm.elements['ans'].value;
</script>
You have two elements with the same ID, causing a name conflict. They're also the same as the name attribute on the same element, which could cause some confusion down the road.
Try:
var ansVal = myForm.ans.checked;
This will work:
function submitAnswer() {
var myForm = document.getElementById('quiz');
// Set a default value, in case no radio button is selected
var ansVal = 'default value here';
var qnoVal = myForm.qno.value;
// Loop through radio buttons, getting the value of the
// one that is checked (selected).
var radioButtons = myForm.ans;
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
ansVal = radioButtons[i].value;
}
}
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
this will work too
function submitAnswer()
{
var myForm = document.getElementById('quiz');
var qnoVal = myForm.qno.value;
var ansVal = 'none';
for( i = 0; i < myForm.ans.length; i++ )
{
if( myForm.ans[i].checked == true )
{
ansVal = myForm.ans[i].value;
break;
}
}
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
This will work
<html>
<form name="form">
Which one is good?<br>
<input type="radio" name="food" value="Spud"
checked="checked"> Spud<br>
<input type="radio" name="food" value="Carrot"> Carrot<br>
<input type="submit" onclick="get_radio_value()">
</form>
<script type="text/javascript>
<!--
function get_radio_value()
{
for (var i=0; i < document.form.food.length; i++)
{
if (document.form.food[i].checked)
{
var rad_val = document.form.food[i].value;
alert(rad_val);
}
}
}
//-->
</script>
</html>