How to use data-display with multiple inputs? - javascript

I have a form wizard, in the last step I want display a preview of the form data submitted. I'm using data-display attribute to do that. I have multiple inputs with same name:
<input type="text" class="form-control input_nb" name="num_espece[]" placeholder="Indiquer le nombre">
and this is how I display in the final step:
<p class="form-control-static display-value" data-display="num_espece[]"></p>
and this is the script used for that:
f = function() {
$(".display-value", form).each(function() {
var a = $('[name="' + $(this).attr("data-display") + '"]', form);
"text" == a.attr("type") || "email" == a.attr("type") || a.is("textarea") ? $(this).html(a.val()) : a.is("select") ? $(this).html(a.find("option:selected").text()) : a.is(":radio") || a.is(":checkbox") ? $(this).html(a.filter(":checked").closest("label").text()) : "card_expiry" == $(this).attr("data-display") && $(this).html($('[name="card_expiry_mm"]', form).val() + "/" + $('[name="card_expiry_yyyy"]', form).val())
})
},
When I'm in the preview step I get only the value of the first input displayed. What should I do to get the values of all inputs displayed ?

Welcome Youssef, if I understood you well, you want everything inside your form to be shown after submit
Let's suppose this is your form
<form>
<input placeholder="Your name" required>
<input type="email" placeholder="Your email" required>
<textarea placeholder="Your comment"></textarea>
<button>Check</button>
</form>
You just need to get all items and show their values.
// Avoid submit button
const $items = document.querySelectorAll('form > *:not(button)')
// On submit
document.querySelector('form').onsubmit = e => {
// Show all data
document.body.innerHTML = [...$items].reduce((acc, e) =>
acc += `${e.placeholder} = ${e.value}<br>`, '')
// Aborting real submit, this is just an example
e.preventDefault()
}
Instead of document.body you can use document.querySelector('p.display-value')
https://jsfiddle.net/3mc29vyj/
Hope this help or at least point you to the right direction : )

If I understood you correctly you want to add all input values into one <p> tag, right?
Right now you iterate over all <p class="display-value"> tags and then find all elements with the same name provided in the data-display attribute. Your var a now contains a list of elements but in your code you treat it as a single element. You need to loop over all fields and append the values to the display element, $(this).html(...) will overwrite it so you want to append the text via $(this).append(...).
Code sample
f = function() {
var form = $("form");
$(".display-value").each(function() {
$(this).html('');
var as = $('[name="' + $(this).data("display") + '"]');
if (as && as.length) {
for (var i = 0; i < as.length; i++) {
var a = $(as[i]);
"text" == a.attr("type") ||
"email" == a.attr("type") ||
a.is("textarea")
? $(this).append(a.val())
: a.is("select")
? $(this).append(a.find("option:selected").text())
: a.is(":radio") || a.is(":checkbox")
? $(this).append(
a
.filter(":checked")
.closest("label")
.text()
)
: "card_expiry" == $(this).attr("data-display") &&
$(this).append(
$('[name="card_expiry_mm"]', form).val() +
"/" +
$('[name="card_expiry_yyyy"]', form).val()
);
}
}
});
};
A demo can be found in this Codepen.

Related

How to display input values from textfields with array name attributes using javascript

I have created a form which should submit data, but before submission I want the user to have a preview of what they have filled before clicking on the submit button.
The JavaScript function I have put in place, only shows input values from only one of the textfield.
what I expect was that for each textfield I would get its input values displayed.
Currently, I am getting just one value from the textfields with this same id.
How can I adjust my code to show value of each textfield .
// function and element to view input value
function myFunction() {
var Milstonedescription =
document.getElementById("milstanedetails").value;
document.getElementById("Milestonesdescriptionvalue").innerHTML =
Milstonedescription;
}
<input type="text" class="milstone" id="milstanedetails" placeholder="Describe the milestone or task you will complete" oninput="myFunction()" name="milestone[]">
<input type="text" class="milstone" id="milstanedetails" placeholder="Describe the milestone or task you will complete" oninput="myFunction()" name="milestone[]">
<p class="halffieldcontainer" id="Milestonesdescriptionvalue"></p>
The problem on your code is that you use the same id on multiple input field, thats not possible because id are unique and whatever you will get only the first element with the matching id.
If you want to get your value from each fields you should use getElementsByClassName('className') and looping on, it's seems to correspond to what you want to do.
EDIT :
Yeah last version didn't work properly, i edited and tested that one. Seems to work properly on my side now. ( http://jsfiddle.net/tgo46se2/ )
function myFunction() {
let milstones = document.getElementsByClassName("milstone");
let milstoneDescription = '';
for(let i = 0; i < milstones.length; ++i) {
milstoneDescription += milstones[i].value;
}
document.getElementById("Milestonesdescriptionvalue").innerHTML = milstoneDescription;
}
this could works:
<!doctype html>
<head></head>
<body>
<p id="text"></p>
<input type="text" class="milstone" id="milstanedetails" placeholder="Describe the milestone or task you will complete" oninput="myFunction('milstanedetails','Milestonesdescriptionvalue')" name="milestone[]">
<input type="text" class="milstone" id="milstanedetails2" placeholder="Describe the milestone or task you will complete" oninput="myFunction('milstanedetails2', 'Milestonesdescriptionvalue')" name="milestone[]">
<p class="halffieldcontainer" id="Milestonesdescriptionvalue"></p>
</body>
<script>
// function and element to view input value
function myFunction(idEl, idPrev) {
var Milstonedescription =
document.getElementById(idEl).value;
document.getElementById(idPrev).innerHTML =
Milstonedescription;
}
</script>
</html>
I change the second id because in html id must be unique.
I hope this help
first, you have to make each input id unique because using the same id value for multiple elements is not valid in HTML.
you can achieve what you want by this code:
function myFunction(){
var nodes = document.querySelectorAll("[name='milestone[]']");
var input_value1 = nodes[0].value;
var input_value2 = nodes[1].value;
var text = '';
if(input_value1 && input_value1 !== ''){
text += 'first input value: ' + input_value1;
}
if(input_value2 && input_value2 !== ''){
text += '<br /> second input value: ' + input_value2;
}
document.getElementById("Milestonesdescriptionvalue").innerHTML = text;
}
<input type="text" class="milstone" id="milstanedetails1" placeholder="Describe the milestone or task you will complete" oninput="myFunction()" name="milestone[]">
<input type="text" class="milstone" id="milstanedetails2" placeholder="Describe the milestone or task you will complete" oninput="myFunction()" name="milestone[]">
<p class="halffieldcontainer" id="Milestonesdescriptionvalue"></p>
and here is a working snippet.
Get inputs by class attribute.
function myFunction() {
var milstones = document.getElementsByClassName("milstone");
var milstoneDescription = '';
for (var i = 0; i < milstones.length; i++) {
var val = milstones[i].value;
if (typeof val != "undefined")
milstoneDescription += val + ' ';
}
document.getElementById("Milestonesdescriptionvalue").innerHTML = milstoneDescription;
}

Add suffix to form field

I have some (more than thousand) users that insist on logging in just with their names, but a system that insists on having the full e-mail address (name + #my-mail.com) provided. Which is a smart solution to add a suffix to a field without bothering the user?
The Form:
<form id="login_form" action="processing.php" method="post" class="form">
<fieldset>
<ul class="input_block">
<li>
<input type="text" name="email" id="email" value="" />
</li>
<li>
<input type="password" name="passwort" id="password" />
</li>
</ul>
</fieldset>
I played around with the key up function for the field, but it didn't help much.
<script>
$('#email').keyup(function(e){
if(this.value.length > 12){
this.value = this.value + '#my-mail.com';
if( this.value.indexOf('#my-mail.com') <= 0 ){
this.value = String.fromCharCode(e.which) + '#my-mail.com';
}
});
</script>
I consider a solution that manipulates the field just right before the submission much more "proper" (sadly I don't have access to the PHP file that is receiving the submission). So I tried as well with the submit function, this didn't work either.
<script>
$( "#login_form" ).submit(function( event ) {
("#email").value = ("#email").value + '#my-mail.com';
});
</script>
Anybody some advise on how to solve it using the submit function or another idea that seems to be better?
$('#email').change(function() {
var val = $(this).val();
if(val.indexOf('#my-mail.com') == -1)
$(this).val(val+'#my-mail.com');
});
http://jsfiddle.net/g4oLtfw7/
This will add the '#my-mail.com' suffix if it's not already part of the input value. If you want to allow other types of emails, but default to 'my-mail.com' otherwise, try this:
$('#email').change(function() {
var val = $(this).val();
if(val.indexOf('#') == -1)
$(this).val(val+'#my-mail.com');
});
Either:
$('#login_form').submit(function (e) {
var email = $('#email'),
user = email.val().split('#')[0],
domain = '#my-mail.com';
if (email.val().toLowerCase() !== (user + domain).toLowerCase()) {
email.val(user + domain);
}
});
or
$('#email').change(function (e) {
var email = $(this),
user = email.val().split('#')[0],
domain = '#my-mail.com';
if (email.val().toLowerCase() !== (user + domain).toLowerCase()) {
email.val(user + domain);
}
});
is how I would approach this (obligatory fiddle: http://jsfiddle.net/e84v7nat/).
This approach ensures that your user has a domain specified and that the domain is correct. If the username is case-sensitive, remove the calls to .toLowerCase.

shorten querystring for searching and many filters

i am building a search function which use many filters. i decide to use the get method instead of post (different reasons). Problem is, when using many filters the querystring gets very long, especially when i use filter with same name so i get
myurl.com?filter1[]=val1&filter1[]=val2&filter2=val
To get better control and to prevent 0 values i tried serializeArray:
var array = {};
jQuery.each(jQuery('form').serializeArray(), function(index,val) {
if (val.value != 0 )
array[value.name] = val.value;
});
But this way it overrides the first filter1 with the last value of filter1, so multiple values doesn´t work. And then i have the "problem" to create the querystring. I am not a javascript prof. so i need a little help here.
What can i do, so i get a querystring which looks like:
myurl.com?filter1=val1|val2&filter2=val and so on
The HTML are "normal" input fields
<input type="checkbox" name="filter1[]" />
<input type="text" name="filter2" />
Thank you in advance
ruven
How about this (working demo):
<form action="search.html">
<input type="text" value="val1" name="filter1" />
<input type="text" value="val2" name="filter1" />
<input type="text" value="val" name="filter2" />
<input type="submit" value="search" name="cmdSearch" />
</form>
​
<script>
// don't do anything until document is ready
$(function() {
// register to form submit event
$('form').submit(function(e){
// stop the form from doing its default action (submit-GET)
e.preventDefault();
// initialise url
var url = '';
// keep track of previously enumerated field
var prev = '';
// iterate all fields in the form except the submit button(s)
$('input:not([type="submit"])', $(this)).each(function(){
// get the name of this field, with null coalesce
var name = $(this).attr('name') || '';
// get the value of this field
var val = $(this).attr('value');
// does this field have the same name as the previous?
if (name.toLowerCase() == prev.toLowerCase()) {
// same name therefore we have already appended the name
// append value separator
url += '|';
}
else {
// different name, track new name
prev = name;
// append parameter separator, parameter name, equals char
url += '&' + name + '=';
}
// append value of this field
url += val;
});
// removing leading ampersand
if (url.length && [0] == '&') {
url = url.substring(1);
}
// insert leading question mark
url = '?' + url;
// insert url from "action" attribute of the form
url = $(this).attr('action') + url;
// display url (delete this line)
alert(url);
// redirect to the new url (simulates the GET)
window.location.href = url;
});
});
</script>

jquery and javascript mix: How to pass the name to jquery selector

I want to slide some jquery into a piece of another programmers javascript code that I have to work worth. Can I do this? Look at the code for the 'radio'.
function blank(field) {
if ((field.type == "text" || field.type == "textarea") && (field.value == " " || field.value == ""))
{
return true;
}
else if field.type = "radio"
{
$('input[type='radio', **name=passField.NameHere**]:checked').size() > 0);
}
}
so in the above I want to use jquery to see if anything in a radio group has been checked.
Example of radio code:
<input type="radio" name="2074" id="2074" value="Yes" class="valuetext>Yes
<input type="radio" name="2074" id="2074" value="No" class="valuetext>No
I want to pass the field.name which has already been captured in another function, into the jquery call. Is this possible? If so, how?
Below is the function that gathers the fields that need to be exampled:
var field = [], blankFields = [],
listText = [], listItem = [], fieldId = [], label = [];
function checkRequired(fieldList) {
for (var i = 0; i < fieldList.length; i++)
{
listText = fieldList[i];
listText = listText.substring(1, listText.length - 1);
listItem = listText.split("||");
fieldId = listItem[0];
label = listItem[1];
field = document.getElementById(fieldId);
if (visible(field) && blank(field)){
blankFields.push(label);
}
}
//return blankFields;
if (blankFields.length > 0) {
displayError(blankFields);
}
}
Any help would be appreciated.
Yes, it looks like field is the actual DOM object, so:
$('input[type="radio"][name="' + field.name + '"]:checked').size() > 0);
Note that you have several syntax errors in the code other than the obvious place you were calling out a placeholder. For instance:
else if field.type = "radio"
You need parens around the condition, and = should be == or ===.
Also note that I changed ' to " in a couple of places, because originally you had:
$('input[type='radio']...
...which ends the string just after type=, since the string started with ' and therefore ends with '.

Dynamic Form Input Based on Anchor Value

I have the following snippets that open a single Modal Form:
<a class="modalbox" id="foo" href="#inline">Request a Quote</a>
<a class="modalbox" id="bar" href="#inline">Request a Quote</a>
...and so on...
Somehow, I need to render the value of ID in the input "sub" in the following HTML form
as well as concatenate the ID with some predetermined text, which is "I am interested in..."
<form id="contact" name="contact" action="#" method="post">
<input type="hidden" id="product" name="product" value="">
<label for="sub">Subject:</label>
<input type="sub" id="sub" name="sub" class="txt" value="I am interested in '$id'">
<button id="send">Submit</button>
I'm already using Javascript for verification and AJAX for processing to PHP script.
Edit:
This is the Javascript already being used to populate the hidden input above, which is working perfectly:
$('a').click(function(e) {
$('#product').val($(this).attr('id'));
I'd suggest, with plain JavaScript, something like:
function addTextToInput(from, to, prefix, e) {
e = e || window.event;
if (!from || !to) {
return false;
}
else {
from = from.nodeType == 1 ? from : document.getElementById(from);
to = to.nodeType == 1 ? to : document.getElementById(to);
var text = from.id;
to.value = prefix ? prefix + ' ' + text : text;
}
}
var as = document.querySelectorAll('a.modalbox');
for (var i = 0, len = as.length; i<len; i++) {
as[i].onclick = function(e) {
addTextToInput(this, 'sub', 'I am interested in', e);
};
}​
JS Fiddle demo.
But given that you already seem to be using jQuery:
$('a.modalbox').click(function(e){
e.preventDefault();
$('#sub').val('I am interested in ' + this.id);
});
JS Fiddle demo.

Categories

Resources