Get the containers with inputs and their values - javascript

I need to get a DOM container (entire HTML code inside it), inside it has some input texts. When I save this DOM in the database the input values are not there.
I have tried:
$(".container").html()
$(".container").prop('outerHTML')
$(".container").text()
$(".container").get(0).outerHTML
Example:
As it is in the database now:
<div class="container stackExemple">
<input type="text" name="1">
<input type="text" name="2">
<input type="text" name="3">
<input type="text" name="4">
</div>
As i need it to be:
<div class="container stackExemple">
<input type="text" name="1" value="value1">
<input type="text" name="2" value="value2">
<input type="text" name="3" value="value3">
<input type="text" name="4" value="value4">
</div>

You should set the value attribute using .each() and .attr()
$(".container [type=text]").each(function(i){
$(this).attr('value', 'value'+(i+1));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container stackExemple">
<input type="text" name="1">
<input type="text" name="2">
<input type="text" name="3">
<input type="text" name="4">
</div>

How about writing the val() back as a value attribute on demand?
$('#test').on('click',function(){
var $container = $('.container');
$('input',$container).each(function(){
$(this).attr('value',$(this).val());
});
console.log($container.html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container stackExemple">
<input type="text" name="1">
<input type="text" name="2">
<input type="text" name="3">
<input type="text" name="4">
</div>
<button id="test">Click for html</button>

Updating the html attribute value will update the value of the input, but updating the the value of the input, will not update the html attribute.
The trick is to update the value attribute of the elements before you read the html.
$("#print").on("click", function() {
$("#results").text(JSON.stringify(getContainer(), (key, value) => (!key || !isNaN(key)) ? value : undefined, 4).replace(/\\n/g, "\n").replace(/\\"/g, "'"));
});
function getContainer() {
return $(".container").map(function() {
$("input", this).each(function() {
this.setAttribute("value", this.value);
});
return this.outerHTML;
});
}
#results {
display: block;
white-space: pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container stackExemple">
<input type="text" name="1">
<input type="text" name="2">
<input type="text" name="3">
<input type="text" name="4">
</div>
<div class="container stackExemple">
<input type="text" name="5">
<input type="text" name="6">
<input type="text" name="7">
<input type="text" name="8">
</div>
<button id="print">Print</button>
<code id="results"></code>

Related

Count number of inputs and sum depending on its values

I would like to do two things:
I want to count the number of inputs that have a value. (doesn't matter if the value is A or X).
Then, count the number of inputs whose value is equal to A
therefore, the results should contain 6 of 14 items
This is what I tried to count the inputs that already have value:
var filledInputs = $(".col input").filter(function() {
return !!this.value;
}).length;
const test2 = document.querySelectorAll(".result");
test2.forEach((item) => {
item.innerHTML = filledInputs;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<div class="col">
<input type="text" value="A">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text">
<input type="text">
<input type="text">
</div>
<div class="results"></div>
One possible implementation with jQuery:
let any = 0;
let a = 0;
$(".col input").each((idx, item) => {
if (!item.getAttribute("value")) {
return;
}
if (item.getAttribute("value") == "A") {
a += 1;
}
any += 1;
});
$(".results").html(a + " of " + any + " items")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<input type="text" value="A">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text">
<input type="text">
<input type="text">
</div>
<div class="results">
6 of 14 items
</div>
Use the same logic that you made to find the filled inputs, to find the inputs with value A
const filledInputs = $(".col input").filter(function () {
return !!this.value;
}).length;
const inputWithValA = $(".col input").filter(function () {
return this.value === 'A';
}).length;
console.log(filledInputs)
console.log(inputWithValA)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<div class="col">
<input type="text" value="A" />
<input type="text" value="A" />
<input type="text" value="X" />
<input type="text" value="X" />
<input type="text" value="A" />
</div>
<div class="col">
<input type="text" value="A" />
<input type="text" value="X" />
<input type="text" value="A" />
</div>
<div class="col">
<input type="text" value="X" />
<input type="text" value="X" />
<input type="text" value="A" />
</div>
<div class="col">
<input type="text" />
<input type="text" />
<input type="text" />
</div>
<div class="results">6 of 14 items</div>
var $inputs = $(".col input").filter(function() {
return !!$(this).val();
});
var inputsFilled = $inputs.length
var inputsA =$inputs.filter(function() {
return $(this).val() == 'A';
}).length
console.log(inputsFilled)
console.log(inputsA)
$(".results").html(`${inputsA} of ${inputsFilled} are A`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<input type="text" value="A">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text">
<input type="text">
<input type="text">
</div>
<div class="results"></div>
Here's a minimal solution:
var AInputs = $(":input[value='A']").length;
console.log(AInputs);
Full snippet:
var filledInputs = $(".col input").filter(function() {
return !!this.value;
}).length;
console.log(filledInputs);
var AInputs = $(":input[value='A']").length;
console.log(AInputs);
const test2 = document.querySelectorAll(".result");
test2.forEach((item) => {
item.innerHTML = filledInputs;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<input type="text" value="A">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text">
<input type="text">
<input type="text">
</div>
<div class="results"></div>
Don't mix DOM and jQuery like that
You are looping over one element
Perhaps you meant this:
const $breakdown = $("#breakdown");
const $results = $(".results")
let totalA = 0;
let totalNonEmptyInput = 0;
$(".col").each(function(i, ele) {
const $inputs = $(ele).find("input");
let As = 0;
const notEmpty = $inputs.filter(function() {
const val = this.value.trim();
if (val === "A") {
As++;
totalA++;
}
totalNonEmptyInput += val !== "";
return val !== ""
}).length;
$results.html(`${totalA} of ${totalNonEmptyInput}`)
$breakdown.append(`<li>${(i+1)}: ${notEmpty}/${$inputs.length} - found ${As} A</li>`)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<input type="text" value="A">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text">
<input type="text">
<input type="text">
</div>
<div class="results"></div>
<ul id="breakdown"></ul>
const cols_ = document.querySelectorAll('.col');
let inputs_val_a = []; // matched input will stored here
cols_?.forEach(function(col,col_i){
col.querySelectorAll('input')?.forEach(function(ipt, ipt_i){
if( ipt.value == 'A' ){
// match
console.log('cols:'+col_i+' input:'+ipt_i+' have value "A"');
inputs_val_a.push(ipt);
}
})
});
document.querySelector('.results').innerHTML = 'there is '+ inputs_val_a.length + ' inputs with value == A';
<div class="results"></div>
<div class="col">
<input type="text" value="A">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text">
<input type="text">
<input type="text">
</div>
Maybe the easiest method (and marginally more performant than filtering) in vanilla JS is to do three selections: one on all inputs, and then two selections using the value attribute.
const inputs = document.querySelectorAll('input');
const inputsAll = document.querySelectorAll('[value]');
const inputsA = document.querySelectorAll('[value="A"]');
console.log(`${inputsAll.length} of ${inputs.length} items`);
console.log(`${inputsA.length} of ${inputs.length} items`);
<div class="col"> <input type="text" value="A"> <input type="text" value="A"> <input type="text" value="X"> <input type="text" value="X"> <input type="text" value="A"></div><div class="col"> <input type="text" value="A"> <input type="text" value="X"> <input type="text" value="A"></div><div class="col"> <input type="text" value="X"> <input type="text" value="X"> <input type="text" value="A"></div><div class="col"> <input type="text"> <input type="text"> <input type="text"></div><div class="results"></div>
If you want updated counts while you are filling in the fields you could recalculate it in an event driven function:
const inps=$(".col input").get();
$("body").on("input",".col input",upd8);
function upd8(){
[any,A]=inps.reduce((a,c)=> (c.value&&++a[0]&&c.value.toUpperCase()=="A"&&++a[1],a),[0,0]);
$(".results").html(A + " of " + any + " items")
};
upd8();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<input type="text" value="A">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text">
<input type="text">
<input type="text">
</div>
<div class="results">
6 of 14 items
</div>

Dynamically target specific DIV´s with unique ID in Ajax

Say that I have more than 100 forms on one page (I know it is a lot, but neccesary in this matter) and I have a Ajax that submit each forms without reloading the page it is in, and Show/Hide a DIV on callback from jQuery on success and error, how do I:
1 : Target the specific DIV ID in the jQuery
2 : Make sure that it submit the specific form and only this form (not validating on required fields from other forms)
JS Code:
<script>
$("form").on("submit", function(e) {
var dataString = $(this).serialize();
let response_div = $("[id^='response_div_']")
$.ajax({
type: "POST",
url: "update_userdata.asp",
data: dataString,
success: function() {
response_div.html("<div id='message' style='background-color: #28a745;'></div>");
$("#message")
.html("<font style='color: white;'>Løn Information er nu opdateret <i class='fas fa-check-circle'></i></font>")
.hide()
.fadeIn(1500, function() {
$("#message").append(
""
);
});
}
});
e.preventDefault();
});
</script>
HTML:
<div id="response_div_initials_1">
</div>
<form name="Initials2" id="Initials2" action="">
<input type="hidden" name="UserID" id="UserID" value="1">
<input type="hidden" name="ColumnToUpdate" id="ColumnToUpdate" value="InitialsColumn">
<fieldset>
<div class="input-box">
<label for="Initials" id="Initials">Initials</label>
<input type="text" name="Initials" id="Initials" minlength="3" maxlength="3" class="text-input" required/>
</div>
<button type="submit" form="Initials2" value="Submit">Send</button>
</fieldset>
</form>
<div id="response_div_EconomyColumns_1">
</div>
<form name="EconomyColumns1" id="EconomyColumns1" action="">
<input type="hidden" name="UserID" id="UserID" value="1">
<input type="hidden" name="ColumnToUpdate" id="ColumnToUpdate" value="EconomyColumns">
<fieldset>
<div class="input-box">
<label for="lonnr" id="lonnr_label">lonnr</label>
<input type="text" name="lonnr" id="lonnr" minlength="3" class="text-input" required/>
</div>
<div class="input-box">
<label for="debnr" id="debnr_label">debnr</label>
<input type="text" name="debnr" id="debnr" class="text-input"/>
</div>
<div class="input-box">
<label for="orgnr" id="orgnr_label">orgnr</label>
<input type="text" name="orgnr" id="orgnr" class="text-input"/>
</div>
<button type="submit" form="EconomyColumns1" value="Submit">Send</button>
</fieldset>
</form>
<div id="response_div_initials_2">
</div>
<form name="Initials2" id="Initials2" action="">
<input type="hidden" name="UserID" id="UserID" value="1">
<input type="hidden" name="ColumnToUpdate" id="ColumnToUpdate" value="InitialsColumn">
<fieldset>
<div class="input-box">
<label for="Initials" id="Initials">Initials</label>
<input type="text" name="Initials" id="Initials" minlength="3" maxlength="3" class="text-input" required/>
</div>
<button type="submit" form="Initials2" value="Submit">Send</button>
</fieldset>
</form>
<div id="response_div_EconomyColumns_2">
</div>
<form name="EconomyColumns1" id="EconomyColumns1" action="">
<input type="hidden" name="UserID" id="UserID" value="1">
<input type="hidden" name="ColumnToUpdate" id="ColumnToUpdate" value="EconomyColumns">
<fieldset>
<div class="input-box">
<label for="lonnr" id="lonnr_label">lonnr</label>
<input type="text" name="lonnr" id="lonnr" minlength="3" class="text-input" required/>
</div>
<div class="input-box">
<label for="debnr" id="debnr_label">debnr</label>
<input type="text" name="debnr" id="debnr" class="text-input"/>
</div>
<div class="input-box">
<label for="orgnr" id="orgnr_label">orgnr</label>
<input type="text" name="orgnr" id="orgnr" class="text-input"/>
</div>
<button type="submit" form="EconomyColumns1" value="Submit">Send</button>
</fieldset>
</form>
I tried different variations of $("[id^='response_div_']") but havent had success with any attempts I have tried.
If you have 100+ form, I would suggest event delegation for one event listener listens multiple forms.
If those response_div_ are just for displaying message to a specific form, but not for storing data, I suggest you to not setting a unique id to them. Instead, I move the response div under the form and set it with form_response class so you know which div to update.
I also put the styling into <style> so you don't need to handing css inside the script.
I usually don't write html within string literal. To have a icon after the response message, you can offload it to CSS which makes your script neater. Check the form_response::after style. Font awesome has an article on that.
p.s. you need to fix the submit button and form name. There are 2 EconomyColumns1 and Initials2 form.
$('html').on('submit', 'form', function(e) {
e.preventDefault();
var dataString = $(this).serialize();
// obtain the submitting form with e.currentTarget
// then search the tree down for div with class form_response
let responseDiv = $(e.currentTarget).children('div.form_response');
$.ajax({
type: "POST",
url: "https://6049aeb7fb5dcc001796a5ad.mockapi.io/foobar", // mock api for testing
data: dataString,
success: function() {
$(responseDiv)
.html("Løn Information er nu opdateret")
.hide()
.fadeIn(1500, function() {
// what is this line for?
$("#message").append("");
})
// wait 5 second
.delay(5000)
// fade out
.fadeOut(1500);
}
});
});
.form_response {
display: none;
background-color: #28a745;
color: white;
}
.form_response::after {
font-family: "Font Awesome 5 Free";
content: "\f058";
font-weight: 900;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="Initials2" id="Initials2" action="">
<div class="form_response"></div>
<input type="hidden" name="UserID" id="UserID" value="1"> <input type="hidden" name="ColumnToUpdate" id="ColumnToUpdate" value="InitialsColumn">
<fieldset>
<div class="input-box">
<label for="Initials" id="Initials">Initials</label> <input type="text" name="Initials" id="Initials" minlength="3" maxlength="3" class="text-input" required />
</div>
<button type="submit" form="Initials2" value="Submit">Send</button>
</fieldset>
</form>
<form name="EconomyColumns1" id="EconomyColumns1" action="">
<div class="form_response"></div>
<input type="hidden" name="UserID" id="UserID" value="1"> <input type="hidden" name="ColumnToUpdate" id="ColumnToUpdate" value="EconomyColumns">
<fieldset>
<div class="input-box">
<label for="lonnr" id="lonnr_label">lonnr</label> <input type="text" name="lonnr" id="lonnr" minlength="3" class="text-input" required />
</div>
<div class="input-box">
<label for="debnr" id="debnr_label">debnr</label> <input type="text" name="debnr" id="debnr" class="text-input" />
</div>
<div class="input-box">
<label for="orgnr" id="orgnr_label">orgnr</label> <input type="text" name="orgnr" id="orgnr" class="text-input" />
</div>
<button type="submit" form="EconomyColumns1" value="Submit">Send</button>
</fieldset>
</form>
<form name="Initials2" id="Initials2" action="">
<div class="form_response"></div>
<input type="hidden" name="UserID" id="UserID" value="1"> <input type="hidden" name="ColumnToUpdate" id="ColumnToUpdate" value="InitialsColumn">
<fieldset>
<div class="input-box">
<label for="Initials" id="Initials">Initials</label> <input type="text" name="Initials" id="Initials" minlength="3" maxlength="3" class="text-input" required />
</div>
<button type="submit" form="Initials2" value="Submit">Send</button>
</fieldset>
</form>
<form name="EconomyColumns1" id="EconomyColumns1" action="">
<div class="form_response"></div>
<input type="hidden" name="UserID" id="UserID" value="1"> <input type="hidden" name="ColumnToUpdate" id="ColumnToUpdate" value="EconomyColumns">
<fieldset>
<div class="input-box">
<label for="lonnr" id="lonnr_label">lonnr</label> <input type="text" name="lonnr" id="lonnr" minlength="3" class="text-input" required />
</div>
<div class="input-box">
<label for="debnr" id="debnr_label">debnr</label> <input type="text" name="debnr" id="debnr" class="text-input" />
</div>
<div class="input-box">
<label for="orgnr" id="orgnr_label">orgnr</label> <input type="text" name="orgnr" id="orgnr" class="text-input" />
</div>
<button type="submit" form="EconomyColumns1" value="Submit">Send</button>
</fieldset>
</form>
This is what you want...?
the HTML
<h2>Form 1</h2>
<form>
<div class="message"></div>
<input type="text" name="name-a">
<button type="submit">Submit</button>
</form>
<h2>Form 2</h2>
<form>
<div class="message"></div>
<input type="text" name="name-b">
<button type="submit">Submit</button>
</form>
then jQuery
$('form').submit(function(e){
e.preventDefault();
let data = $(this).serialize();
let msgBox = $(this).find('.message');
$.ajax({
type: 'POST',
url: 'update_userdata.asp',
data: dataString,
success: function(){
msgBox.html("Put your html message here that will display according to the submited form");
// Once we have the message we show the message box
msgBox.css('display', 'block');
}
});
});
and some CSS
.message {
border: 1px solid red;
padding: 4px;
text-align: center;
width: 100px;
margin: 4px;
display: none;
}
the working demo https://jsfiddle.net/jozsefk/1yw7c9x3/ Please note, that this is just an example to show you how to do it and you must adapt this to your code.
Also this will display your input name and value if exists based on a form submited.
Here is the code I have last tried:
<div class="message" style="background-color: #28a745;"></div>
</div>
<form name="Initials1" id="Initials1" action="">
<input type="hidden" name="UserID" id="UserID" value="1">
<input type="hidden" name="ColumnToUpdate" id="ColumnToUpdate" value="InitialsColumn">
<fieldset>
<div class="input-box">
<label for="Initials" id="Initials">Initials</label>
<input type="text" name="Initials" id="Initials" minlength="3" maxlength="3" class="text-input" required/>
</div>
<button type="submit" form="Initials1" value="Submit">Send</button>
</fieldset>
</form>
<script>
$('form').submit(function(e){
e.preventDefault();
let data = $(this).serialize();
let msgBox = $(this).find('.message');
$.ajax({
type: 'POST',
url: 'update_userdata.asp',
data: dataString,
success: function(){
msgBox.html("<p>Hello World!</p>");
// Once we have the message we show the message box
msgBox.css('display', 'block');
}
});
});
</script>
The message CSS from you is still in the doc aswell

Focus next input once reaching maxlength in different containers

I want to focus next input once the input field reach the maxlength, but the input fields are in different containers.
My Code:
$(document).ready(function(){
$('input').keyup(function(){
if($(this).val().length==$(this).attr("maxlength")){
$(this).next().focus();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="date" class="container_date">
<div class="date_day" id="input_day">
<input type="text" maxlength="2" name="input_day" id="1" value="">
</div>
<div class="date_month" id="input_month">
<input type="text" maxlength="2" name="input_month" id="2" value="">
</div>
<div class="date_year" id="input_year">
<input type="text" maxlength="4" name="input_year" id="3" value="">
</div>
</div>
<div id="time" class="container_time">
<div class="time_hour" id="input_hour">
<input type="text" maxlength="2" name="input_hour" id="1" value="">
</div>
<div class="time_minute" id="input_minute">
<input type="text" maxlength="2" name="input_minute" id="2" value="">
</div>
</div>
The Jquery works for input fields in the same div/container, but not in a different one. How to focus also in another div/container?
You could try to get a list of all related input-fields by traversing the DOM up until a certain parent element and looking for each input, determining the current input element and select the next one.
I would propose a different solution: use the tabindex attribute.
div class="date_day" id="input_day">
<input type="text" maxlength="2" tabindex="1" name="input_day" id="1" value="">
</div>
<div class="date_month" id="input_month">
<input type="text" maxlength="2" tabindex="2" name="input_month" id="2" value="">
</div>
<div class="date_year" id="input_year">
<input type="text" maxlength="4" tabindex="3" name="input_year" id="3" value="">
</div>
With this you can create a non-linear movement in regard to the "next" field. The focus can easily be moved to the next one:
$('input').keyup(function(){
if($(this).val().length==$(this).attr("maxlength")){
var tabIndex = +$(this).attr('tabindex');
$('[tabindex=' + (+tabIndex+1) + ']').focus();
}
});
Get the index of the current input by searching the matched elements $('input').index(this) Then you can select the next input in the matched elements with .eq(i+1)
$(document).ready(function(){
$('input').keyup(function(){
if($(this).val().length==$(this).attr("maxlength")){
var i = $('input').index(this);
$('input').eq(i+1).focus();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="date" class="container_date">
<div class="date_day" id="input_day">
<input type="text" maxlength="2" name="input_day" id="1" value="">
</div>
<div class="date_month" id="input_month">
<input type="text" maxlength="2" name="input_month" id="2" value="">
</div>
<div class="date_year" id="input_year">
<input type="text" maxlength="4" name="input_year" id="3" value="">
</div>
</div>
<div id="time" class="container_time">
<div class="time_hour" id="input_hour">
<input type="text" maxlength="2" name="input_hour" id="1" value="">
</div>
<div class="time_minute" id="input_minute">
<input type="text" maxlength="2" name="input_minute" id="2" value="">
</div>
</div>

JQuery: Combine sets of field names and values into an object and then push into an array

I have a form with three sets of fields.
Like this:
<form>
<div class="food">
<input type="text" name="" value="" />
<input type="text" name="" value="" />
<textarea name="" value=""></textarea>
</div>
<div class="drinks">
<input type="text" name="" value="" />
<input type="text" name="" value="" />
<textarea name="" value=""></textarea>
</div>
<div class="gifts">
<input type="text" name="" value="" />
<input type="text" name="" value="" />
<textarea name="" value=""></textarea>
</div>
</form>
How do I combine field names and values in each div into their own json object, push the objects into an array, and then add the array to a hidden input field before submission?
You can use map() and get() to create array and inside you can return object for each div.
var data = $('form > div').map(function() {
var obj = {}
$(this).find('input, textarea').each(function() {
obj[$(this).attr('name')] = $(this).attr('value');
})
return obj;
}).get()
console.log(data)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="food">
<input type="text" name="a" value="1" />
<input type="text" name="b" value="11" />
<textarea name="c" value="111"></textarea>
</div>
<div class="drinks">
<input type="text" name="a" value="2" />
<input type="text" name="b" value="22" />
<textarea name="c" value="222"></textarea>
</div>
<div class="gifts">
<input type="text" name="a" value="3" />
<input type="text" name="b" value="33" />
<textarea name="c" value="333"></textarea>
</div>
</form>

How to add attribute checkbox (checked=true) in array by javarscript or jquery

I want to add attribute checked=true with multiple inputs like this:
<form id="students" method="post">
<div class="row">
<input id="aa" name="a[]" value="Smith" type="text" class="a1" >
<input id="bb" name="b[]" value="Alen" type="text" class="b1" >
<input id="save" name="save[]" value="" type="checkbox" class="ab" disabled="disabled" >
</div>
<div class="row">
<input id="aa" name="a[]" value="" type="text" class="a1" >
<input id="bb" name="b[]" value="" type="text" class="b1" >
<input id="save" name="save[]" value="" type="checkbox" class="ab" >
</div>
<div class="row">
<input id="aa" name="a[]" value="Bill" type="text" class="a1" >
<input id="bb" name="b[]" value="Mark" type="text" class="b1" >
<input id="save" name="save[]" value="" type="checkbox" class="ab" >
</div>
<div class="row">
<input id="aa" name="a[]" value="" type="text" class="a1" >
<input id="bb" name="b[]" value="" type="text" class="b1" >
<input id="save" name="save[]" value="" type="checkbox" class="ab" >
</div>
<div class="row">
<input id="aa" name="a[]" value="Kell" type="text" class="a1" >
<input id="bb" name="b[]" value="Keith" type="text" class="b1" >
<input id="save" name="save[]" value="" type="checkbox" class="ab" >
</div>
<input type="submit" value="submit" id="submitbutton" class="insert" onclick="checkform()"/>
</form>
And each line input has no value I add attribute checked=false of checkbox. How I do. Who can help me? thanks.
This is javaScript :
<script type="text/javascript">
function checkform() {
var myForm = document.forms.students;
var myControls = myForm.elements['a[]'];
for (var i = 0; i < myControls.length; i++) {
if(myControls[i].value==""){
$(".ab").attr("checked", true); //check input had value then
}
}
}
</script>
Your question says: "... I add attribute checked=false..."
But your code says:
$(".ab").attr("checked",true); //not false like the question says
Please tell me that's not it ;)
What about something like this? Check out this JSFiddle.
You can swap them around if I misunderstood and you want inputs with something in them to be checked and not vice versa.
In the fiddle I changed it so that the button click is handled by jquery instead of the onClick() attribute of the input.
function checkform() {
var myForm = document.forms.students;
$(myForm).find('input[name="a[]"], input[name="b[]"]').filter(function(){
if(!$.trim(this.value)){
$(this).siblings('.ab').prop('checked', true)
}else{
$(this).siblings('.ab').prop('checked', false)
}
});
}
I also updated it to check both a[] and b[].
Additionally, I removed the myControls variable since you don't need it here.

Categories