.text() removes all input values - javascript

I have form that users fill out a set of checkmarks and when they click a button, the output is a sequence of notes. In this form, a div in my HTML is set up to pull a list of items which will appear in an email. Sometimes, the user needs to fill out an empty text box for one of the items. However, the way the code is written currently, I can get the text for items on the page, but it removes all the text inside the text boxes. Is there a way to include the text boxes too? Here is the code sample:
HTML
<div>
<p>
<input type="checkbox" class="DocsNeeded"> This <input class="DocsNeeded" checked="checked" type="text" size="20" /> information is an example of an item with an input field<br><br>
</p>
</div>
<div>
<p>
<input type="checkbox" class="DocsNeeded"> This is <input type="text" size="20" /> another example of an item with an input field<br><br>
</p>
</div>
JavaScript Function
$(".DocsNeeded:checked:visible").each(function() {
if ($(this).is(":checked")) {
docs += "• " + $(this).parent("p").text().trim() + "\r\n";
}
});
EDIT Based on the questions below:
Essentially the output text (what I'm hoping to get from this question) that the user will then copy and paste into a pre-formatted email will be:
Mr. Person
Here is a list of all the documents that you did not send us
• This [user input here] information is an example of an item with an input field
• This is [user input here] another example of an item with an input field

.text() sets/gets the "text" inside an HTML element. It is not the input type="text". Example close to what you achieve is below. I also included a sample usage of text().
Also, jQuery way of accessing an element's children is to use .children() or .find() (deeper).
$(document).ready(function() {
$('#clickme').click( function() {
var docs = '';
$(".DocsNeeded:checked:visible").each(function() {
if ($(this).is(":checked")) {
docs += "• " +
$(this).parent("p").find('.label-1').text() + ' ' +
$(this).parent("p").find('input[type=text]').val() + ' ' +
$(this).parent("p").find('.label-2').text() + "\r\n";
}
});
$('#result').text(docs);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>
<input type="checkbox" class="DocsNeeded"> <span class="label-1">This</span> <input class="DocsNeeded" checked="checked" type="text" size="20" /> <span class="label-2">information is an example of an item with an input field</span><br><br>
</p>
</div>
<div>
<p>
<input type="checkbox" class="DocsNeeded"> <span class="label-1">This is</span> <input type="text" size="20" /> <span class="label-2">another example of an item with an input field</span><br><br>
</p>
</div>
<button id="clickme">Click Me </button>
<hr />
<div id="result" style="white-space:pre"></div>
<hr />

Related

How can I make the entered text and checkbox text go to the same textfield?

when the project name is entered, it populates in the same text field as the checked boxes text but at the top of the field.
I also want to create a button for sending the completed form if that's possible
html
<div class="name">
<form>
<label for="projectname">Project name:</label>
<input type="text" id="pname" name="pname"><br>
<br>
</div>
<br>
<div class="series1">
<tr><input type="checkbox" rel="textbox1" name="Cabinets" class=test/>
Cabinets</tr>
<input type="checkbox" rel="textbox1" name="Doors" />
Doors
<input type="checkbox" rel="textbox1" name="Drawers">
Drawers
<input type="checkbox" rel="textbox1" name="Drawer Fronts">
Drawer Fronts
<input type="checkbox" rel="textbox1" name="Handles">
Handles
</div>
<textarea id="textbox1" ></textarea>
js
$('input:checkbox').click(function(){
var tb = "#"+$(this).attr('rel');
let text_to_add = this.name + "\n";
//when click a checkbox and show checked items in the text area
if($(this).is(":checked")){
$(tb).append(text_to_add);
}else{
let remove = this.name +"\n";
//when a box is unchecked it clears the previously populated text from checkbox
$(tb).text(function(i, text){
return text .replace(text_to_add,'');
});
}
})
The solution i would come up with will be:
to store the exist value from the textarea everytime you change the text area value.
let existValue = ''
//inside the checkbox click function:
existValue = $(tb).val()
then to add an event listener to the input and everytime the input change to add the e.target.value to the exist value we created before
$('#pname').on('input', (e)=>{
$('#textbox1').val(`${e.target.value}\n${existValue}`)
})
here is a working example: working example

Is there a way to pass the value from a button to a form when the user clicks submit?

I am trying to get the value from 5 buttons, whichever the user selects, and then once they fill the form out, I want the button value that they selected to be shown on the "summary" screen.
Is there a way to get the value of the button, along with all the other form details, and then send all those details to a new screen that shows all the information the user has entered? Something like a confirmation screen to confirm all details before they send their enquiry.
What I've been trying:
Buttons:
<div class="card">
<h1 id="size">Select your size*</h1>
<ul class="size-list">
<li>
<button class="size-link" id="size-button" value="Small">
Small
</button>
</li>
<li>
<button class="size-link" id="size-button2" value="Medium">
Medium
</button>
</li>
<li>
<button class="size-link" id="size-button3" value="Large">
Large
</button>
</li>
<li>
<button class="size-link" id="size-button4" value="X Large">
X Large
</button>
</li>
<li>
<button class="size-link" id="size-button5" value="XX Large">
XX Large
</button>
</li>
</ul>
</div>
I want to get the value from each button above as well as all the information from the form below and send it to the "Summary" screen.
Form:
<form method="GET" action="final.html" id="myform" class="contact-form">
<label id="fullname">Full Name*</label> <br />
<input name="name" id="name" class="txt-form name" type="text" />
<label id="mail">Email*</label> <br />
<input name="email" id="email" class="txt-form email" type="email" />
<label id="cheap">Have you found this item cheaper on a competitor website?*</label>
<br />
<label>
<input id="radio1" type="radio" name="radio" value="Yes"> <label for="radio1">
<span><span></span></span>Yes</label>
<input id="radio2" type="radio" name="radio" value="No"> <label for="radio2">
<span><span></span></span>No</label> <br />
</label>
<div id="url">
<label>Competitor URL</label>
<input name="url_name" id="url-link" class="txt-form" type="url">
</div>
<label id="msg">Enquiry Message*
<span id="characters">(0/200)</span></label>
<textarea name="message" id="message" class="txt-form message" type="textarea"></textarea>
<p id="asterisk">
Fields marked with an *asterisk are compulsory
</p>
<input type="submit" class=" btn" id="submit" value="Submit your enquiry">
</form>
Summary Screen:
<div id="app" class="contact-main">
<form id="myform" class="contact-form"></form>
</div>
Javascript:
const urlName = new URL(location.href);
document.getElementById('app').innerHTML = `
<label>Full Name: </label> ${urlName.searchParams.get("name") || "N/A"}
<br /><br />
<label>Email:</label> ${urlName.searchParams.get("email") || "N/A"}<br /><br />
<label>Size of item selected:</label> ${urlName.searchParams.get("sizes") || "N/A"} <br /><br />
<label>Have you found this item cheaper on a competitor
website?
</label> ${urlName.searchParams.get("radio") || "N/A" } <br /><br />
<div>
<label>Competitor URL:</label> ${urlName.searchParams.get("url-link") || "N/A"} <br /><br />
</div>
<label id="msg">Enquiry Message:</label> <br/> "${urlName.searchParams.get("message") || "N/A"}" <br /><br />
`;
I am able to get everything from the form but the "Size of item selected". I know this is because I am trying to retrieve it from the url.searchPram, however the buttons are not included on the form so I am just wondering if there's any other way?
Regarding: "Is there a way to get the value of the button"
I assume you mean the value of the clicked button. Yes, there is a way, by setting up a click listener.
Rather than setting up a click listener for each button, you can set up just one on the parent that contains the buttons. To make things easy, set an id for the enclosing <ul>:
<ul class="size-list" id="size-list">
Then set a listener on that <ul>:
document.getElementById('size-list').addEventListener('click', evt => {
let clickedButton = evt.target;
let btnValue = clickedButton.value;
}
You now have the value of the clicked button.
Storing Button's Value into a Form Element
If you need to store that value into a form element, so that value is included when the form is submitted, this can also be done with a hidden input. Let's create one with an id and name of "size":
<form method="GET" action="final.html" id="myform" class="contact-form">
<input type="hidden" id="size" name="size" value="" />
</form>
Then, just a slight modification of the click handler will store the button's value into the hidden input:
document.getElementById('size-list').addEventListener('click', evt => {
let clickedButton = evt.target;
let btnValue = clickedButton.value;
document.getElementById('size').value = btnValue;
}
That's all, the "size" value will now be sent when the form is submitted.
SOLUTION:
Add a hidden input on your form for the data. Based on your HTML and JavaScript it would be:
<input type="hidden" id="sizes" name="sizes" value="Medium">
Notice that I added a value attribute of Medium just in case the user hits submit on the form without actually pressing on of the size buttons. You could remove this and add code in your JavaScript to check if sizes is empty/ missing.
Next you need to add a click event listener to each button that will call a function when they are clicked. The JavaScript way:
// Way 1 using older JS.
var buttons = document.querySelectorAll('.size-link');
for( var x = 0; x < buttons.length; x++ ){
buttons[x].addEventListener( 'click', recordButtonSize );
}
// Way 2 using newer JS without an arrow function.
var buttons = document.querySelectorAll('.size-link');
buttons.forEach( function( button ) {
button.addEventListener( 'click', recordButtonSize );
} );
Or directly in the HTML add an onclick to each button:
<button class="size-link" value="..." onclick="recordButtonSize">...</button>
Notice that I removed your ID's. You don't really need them regardless of which solution you choose to use, the JavaScript or HTML.
And now we make the recordButtonSize function that will copy the data from the pressed button over to the hidden input:
function recordButtonSize(){
// Get the element that was clicked on.
var elem = event.target || event.srcElemnt;
// Depending on browsers / where the user clicked we may not be on the button.
if( elem.nodeName != 'BUTTON' ){
elem = elem.closest('button');
}
// Now pull the value from the button and place in the hidden input.
document.getElementById('sizes').value = elem.value;
}
NOTES:
I don't know if button elements care allowed to have value attributes so you may need to switch that to a dataset.
This solution gets the size placed into an input on the form but DOES NOT submit the form. That isn't hard to add but I will leave it as an exercise for you to figure out.
This answer uses a mix of older and newer JavaScript which will work fine on any modern browser but IE 11. See here: closest

onclick Shows <input> text field in form

I am creating a form that will be used to search through a database. The form will have different search criteria in which a user can pick and choose by which variable they want to search (example: name, location, time zone). The form currently has the input type as a button in which I want to create an onclick function that will show an input text field for the user to then enter the value. For example, if the user clicks the "Name" button I want an input text field to appear so that the user can then specify a name. I have tried other ways to get this to work using JavaScript however the values are not being retrieved when I post the form to the PHP file.
an example of the form so far...
<form action="search.php" method="post">
<input type="button" name="name" value="Name" onclick="openInputField()">
<input type="button" name="location" value="location" onclick="openInputField()">
<input type="button" name="timeZone" value="Time Zone" onclick="openInputField()">
javascript for openInputField() is below:
// function that will open input text field when user clicks button
function openInputField(){
var r = document.createElement('span');
var y = document.createElement("INPUT");
y.setAttribute("type", "text");
y.setAttribute("placeholder", "Name");
var g = document.createElement("IMG");
g.setAttribute("src", "delete.png");
increment();
y.setAttribute("Name", "textelement_" + i);
r.appendChild(y);
g.setAttribute("onclick", "removeElement('myForm','id_" + i + "')");
r.appendChild(g);
r.setAttribute("id", "id_" + i);
document.getElementById("myForm").appendChild(r);
}
this opens the text field however upon submit the value is not printing from the PHP file.
$('.form-btn').click(function(){
$(this).next().toggleClass('show-form');
});
.form{
float:left;
list-style:none;
}
.hidden-form{
visibility:hidden;
}
.show-form{
visibility: visible !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="form">
<li>
<input class="form-btn" type="button" name="name" value="Name" >
<input class="hidden-form" type="text" name="nm" >
</li>
</ul>
<ul class="form">
<li>
<input class="form-btn" type="button" name="location" value="Location" >
<input class="hidden-form" type="text" name="loc" >
</li>
</ul>
You can add submit button separately along with the name field.

Display text in order in which a checbox is checked using jquery

**I have a form containing a list of checkboxes. I wish to display some text corresponding to each check box in the order of selection of the check box in another block.And when I deselect a checkbox that text should disappear and if I reselect it it should appear below the existing text. I already checked though many questions in this site. Everywhere there's explanation for the text to appear but not in the order in which the checkbox is checked rather in the order of the checkboxes themselves. I want to do this using html and jquery. Any help towards the direction would be appreciable **
http://jsfiddle.net/jinal1482/Lfuzkkvz/
You can replace 'a' and 'b' with your value or you can retrieve value by other attribute as well.
Html code :
<input type='checkbox' onclick="updateList('a',this)" />
<input type='checkbox' onclick="updateList('b',this)" />
Javascript code :
var options = [];
function updateList(obj,source){
if($(source).attr('checked')){
options.push(obj);
}
else{
options= $.grep(options, function( a ) {
return a !== obj;
});
}
console.log(options);
}
Use a combination of id tag and attribute data-id with the same value in order to connect checkbox and text
http://jsfiddle.net/edobs5cf/
HTML:
<div id="checkbox_div">
<input type='checkbox' data-id="#txt-1" />text 1<br/>
<input type='checkbox' data-id="#txt-2" />text 2<br/>
<input type='checkbox' data-id="#txt-3" />text 3<br/>
<input type='checkbox' data-id="#txt-4" />text 4<br/>
</div>
<div id="text">
<div id="txt-1">text 1</div>
<div id="txt-2">text 2</div>
<div id="txt-3">text 3</div>
<div id="txt-4">text 4</div>
</div>
CSS:
#text div{display:none}
JQ:
$('#checkbox_div input[type="checkbox"]').click(function () {
var $ch = $(this);
var $id = $ch.data('id');
if ($ch.is(':checked')) {
// ensures that the text appears at the end of the list
$($id).appendTo($('#text'));
$($id).show();
} else $($id).hide();
})
Here's a simple example:
HTML:
<input type="checkbox" value="Apple">Apple</input>
<input type="checkbox" value="Banana">Banana</input>
<input type="checkbox" value="Mango">Mango</input>
<input type="checkbox" value="Orange">Orange</input>
<input type="checkbox" value="Grape">Grape</input>
<ul></ul>
JavaScript (jQuery):
$("input").on("change", function (e) {
$("ul").html("");
$("input:checked").each(function () {
$("ul").append("<li>" + this.value + "</li>");
});
});
Given the details in the OP this should be what you're looking for. Basically when one of the inputs (checkboxes) change, we update our list by looping through each checked input. Depending on what you actually want the text to be you would need to modify this example. For each input I would consider putting the text you want to display when an input is clicked in a data attribute. Something like:
<input type="checkbox" value="Apple" data-text="Apples are yummy">Apple</input>
That way in the loop you could grab each inputs data-text attribute and display that instead.

Best way to reorganize arrays index by Dojo/jQuery/Javascript?

I made a list of components that user can add/remove rows of input fields at liberty, so user can freely remove/add a row of data dynamically:
----|_||____| -remove button-
----|_||____| -remove button-
----|_||____| -remove button-
----|_||____| -remove button-
----Add button- ---- Save button ----
However, here comes a problem: the data is arranged in html arrays in order to get back to JSP/sevlet model, like thie
<input id="row[0]" .../>
<input id="row[1]" .../>
<input id="row[2]" .../>
......
<input id="row[n]" .../>
So when user remove a row, especially in the middle of the section, then the array sequence is definitely messed up because I just use basic jquery command to do the job:
if (confirm(message_confirm_delete)) {
j(this).parent().remove();
}
so the question is: what is the best way to re-arrange all of the input fields array, when user remove one of the array elements between?
If I'm understanding your question correctly, you're saying the ids on the input fields are inaccurate after removing one from the middle, correct? If that is the case, something like this will update the id attribute after an element is removed.
<div>
<input id="row[0]" type="text" class="removableInput"/><button class="remove">Remove</button>
</div>
<div>
<input id="row[1]" type="text" class="removableInput"/><button class="remove">Remove</button>
</div>
<div>
<input id="row[2]" type="text" class="removableInput"/><button class="remove">Remove</button>
</div>
<div>
<input id="row[3]" type="text" class="removableInput"/><button class="remove">Remove</button>
</div>
<div>
<input id="row[4]" type="text" class="removableInput"/><button class="remove">Remove</button>
</div>
<div>
<input id="row[5]" type="text" class="removableInput"/><button class="remove">Remove</button>
</div>
<script>
$('button.remove').click(function() {
$(this).parent('div').remove();
$('input.removableInput').each(function(index) {
$(this).attr('id', 'row[' + index + ']');
});
});
</script>

Categories

Resources