So I'm having trouble with JS and how to correctly collect and pass all values from a text field and hidden field on a button click.
<input autocomplete="off" id="add_109_01000340002001010_id" name="add_109_01000340002001010[id]" type="hidden" value="113000674">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001010_name" name="add_109_01000340002001010[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
<input autocomplete="off" id="add_109_01000340002001009_id" name="add_109_01000340002001009[id]" type="hidden" value="112000674">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001009_name" name="add_109_01000340002001009[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
<input autocomplete="off" id="add_109_01000340002001021_id" name="add_109_01000340002001021[id]" type="hidden" value="11405181">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001021_name" name="add_109_01000340002001021[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
Those are text fields and hidden fields with unique ids. They are 'connected'. When you change the value in the text field, the value in the hidden field changes automatically.
When you click on a button, then values that will be written in the text field should be processed in js
function room_group() {
$('.add').bind('click', function() {
var hidden_values = 'something here' // Let's get all values here and pass them to the get request
var values = 'something here' // Let's get all values here and pass them to the get request
$.post('/link/definition', {
val: values,
hidden_val: hidden_values
},
function(response) {
location.reload();
}
);
});
}
The question is how to collect all of those values correctly? Unfortunately, I have no idea...
It depends on how you want to format your values.
You can serialize the values by searching for them with an appropriate selector and then you can create a JSON string as value.
var hiddenValues = JSON.stringify($("input[type='hidden']").serializeArray());
var textValues = JSON.stringify($("input[type='text']").serializeArray());
console.log(hiddenValues);
console.log(textValues);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" value="h1" name="hidden1" />
<input type="hidden" value="h2" name="hidden2" />
<input type="text" value="t1" name="text1" />
<input type="text" value="t2" name="text2" />
Your POST will be something similar to:
var hiddenValues = JSON.stringify($("input[type='hidden']").serializeArray());
var textValues = JSON.stringify($("input[type='text']").serializeArray());
$.post('/link/definition', {
val: textValues,
hidden_val: hiddenValues
},
function(response) {
location.reload();
}
);
Related
I'm in the process of trying to create a simple input form web page using both HTML and JavaScript but I am stuck. What I am trying to do is to ask for the following and display them in the textarea:
-First Name
-Last Name
-CRN
-Professor Name
So far I am only able to get the First Name to show on the Results box but no luck with the other. Could use some help, thanks in advance.
My CODE looks like this:
// initialize the counter and the array
var numbernames=0;
var names = new Array();
function SortNames() {
// Get the name from the text field
thename=document.theform["firstn"].value
// Add the name to the array
names[numbernames]=thename;
// Increment the counter
numbernames++;
document.theform.sorted.value=names.join("\n");
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit"
onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</form>
Here's a complete different, but more readable approach.
I get all inputs of type text.
I get the textarea that is the target.
loop throug all inputs getting it's value.
inside loop, after getting the value, set it to the textarea
Take a look running the snippet below
// initialize the counter and the array
function SortNames() {
var inputs = document.querySelectorAll('input[type="text"]');
var txtArea = document.querySelector('[name="sorted"]');
//loop the text inputs
inputs.forEach(function(elem){
var valueOf = elem.value;
txtArea.value += valueOf + '\n'; //concat the value
});
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit" onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted"></textarea>
</form>
EDIT
If you REALLY want to keep the way you were doing, here's a solution:
1. Push the values from the inputs directly to the array, then set the value inside the textarea.
// initialize the counter and the array
var names = new Array();
function SortNames() {
names.push(document.theform["firstn"].value);
names.push(thename=document.theform["lastn"].value);
names.push(thename=document.theform["crn"].value);
names.push(thename=document.theform["prof"].value);
document.theform.sorted.value=names.join("\n");
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit"
onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</form>
Changed the tags to more semantic and functional tags. Used the HTMLFormControlsCollection API to set/get form controls. The output is a Template Literal.
Details Commented in Demo
Demo
// Reference the top form
const reg = document.forms.registration;
// Reference the bottom form
const dis = document.forms.display;
// Collect all inputs from top form
const f = reg.elements;
// When top form is clicked...
reg.onclick = function(event) {
// Collect the data from each input and store it in an Object
const student = {
First: f.first.value,
Last: f.last.value,
CRN: f.crn.value,
Prof: f.prof.value
};
// Call function
displayData(event, student);
}
function displayData(event, student) {
// Reference the textarea
const view = dis.elements.sorted;
// if the element that was clicked had [name=add]...
if (event.target.name === 'add') {
/* Set the textarea's value to a Template Literal with
|| interpolated values from the student Object.
*/
view.value += `
First: ${student.First}
Last.: ${student.Last}
CRN..: ${student.CRN}
Prof.: ${student.Prof}
~~~~~~~~~~~~~~~~~~~`;
// Otherwise quit
} else {
return false;
}
}
input,
label {
font: inherit;
display: inline-block;
}
label {
width: 20%
}
[type=text] {
width: 75%;
}
[type=reset] {
margin: 5px 0 0 85%;
}
<!DOCTYPE html>
<html lang=”en”>
<head>
<title></title>
</head>
<body>
<form id="registration">
<fieldset id='set0'>
<legend>Registration</legend>
<label>First Name: </label>
<input type="text" name="first" size="10" /><br>
<label>Last Name: </label>
<input type="text" name="last" size="10" /><br>
<label>CRN: </label>
<input type="text" name="crn" size="10" /><br>
<label>Professor: </label>
<input type="text" name="prof" size="10" /><br>
<input type="reset" name="add" value="Submit">
</fieldset>
</form>
<form id='display'>
<fieldset id='set1'>
<legend>View Data</legend>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</fieldset>
</form>
</body>
</html>
I am using MySQL and ajax to pull specific info from a table and then I am passing one of those values to a radio button.
User enters their ID number and it automatically adds the full name, email address and manager from the MySQL table.
I then pass the manager value to a radio button, but it's not working unless I actually click on the manager input field.
I tried, blur, change, keyup, focusin/out but its still not passing the value until I actually click on the input field.
PLEASE NOTE - it works fine if I manually add a value to the manager's field.
Any ideas?
<input type="text" name="id" id="id" value="" >
<input type="text" class="hidden" name="name" id="name" value="" >
<input type="text" class="hidden" name="email" id="email" value="" >
<input type="text" class="hidden" name="manager" id="manager" value="" >
<input type="radio" name="defaultmanager" id="defaultmanager" value="">
<label for="defaultmanager" id="defmanager" >Default manager:</label>
<input type="radio" name="reason" id="otherreason" value="">Other
<input type="text" name="otherreason" />
<script>
$('#manager').bind("change paste keyup", function() {
var val = $(this).val();
$('#defmanager').text('Default Manager:' + val);
});
</script>
Again it works fine but I have to actually click on the input field in order for the value to be passed to the radio button.
Here's the code that automatically adds the name, email and manager:
$(function() {
$( "#id" ).on( 'blur' , function() {
$('#table1 tr').removeClass("hidden");
// getting the value that user typed
searchString=$(this).val();
// forming the queryString
var data = 'telefoon='+searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "query2.php",
data: data,
success: function(html){ // this happens after we get results
result = String(html).split("|");
$("#name").val(result[0]);
$("#email").val(result[1]);
$("#manager").val(result[4]);
}
});
}
return false;
});
});
Where you are programmatically changing the value of the manager field, you need to trigger the change event:
$("#manager").val(result[4]).change();
A full, working example is here:
$('#manager').bind("change paste keyup", function() {
var val = $(this).val();
$('#defmanager').text('Default Manager:' + val);
});
//Set value of the manager field from the database here
$('#manager').val('Bob Marley').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="id" id="id" value="" >
<input type="text" name="name" id="name" value="" >
<input type="text" name="email" id="email" value="" >
<input type="text" name="manager" id="manager" value="" >
<input type="radio" name="defaultmanager" id="defaultmanager" value="">
<label for="defaultmanager" id="defmanager" >Default manager:</label>
<input type="radio" name="reason" id="otherreason" value="">Other
<input type="text" name="otherreason" />
i guess there's a million ways to do everything. I don't know why i wasnt thinking clear. :( Here's what i ended up doing:
$(function() {
$( "#id" ).on( 'blur' , function() {
$('#table1 tr').removeClass("hidden");
// getting the value that user typed
searchString=$(this).val();
// forming the queryString
var data = 'telefoon='+searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "query2.php",
data: data,
success: function(html){ // this happens after we get results
result = String(html).split("|");
$("#name").val(result[0]);
$("#email").val(result[1]);
$("#manager").val(result[4]);
$("#defmanager").val(result[4]);
}
});
}
return false;
});
});
In my web application I have edit profile page. In editprofile page their is many fields like
Name : <input type="text" name="name"/>
Location : <input type="text" class="geolocation" name="location">
Birthdata : <input type="date" name="dob">
Profile Picture : <input type="file" name="photo"/>
I want to send back the data of only the fields which are edited and not all the fields.
I'd normally do something like this on the backend.... but for your requirement you could remove the inputs that haven't changed. When you generate the html you can define an extra data attribute. Here's how I would do that:
HTML:
<form id="myform">
<input type="text" id="Name" data-initial="Foo" value="Foo" />
<input type="text" id="Location" data-initial="Bar" value="Bar" />
<input type="submit" value="Submit" />
</form>
JS:
$("#myform").submit( function() {
$(this).find("input").filter( function() {
$this = $(this);
return $this.data("initial") == $this.val();
}).remove();
});
http://jsfiddle.net/uLe7T/
I added an alert in the fiddle so you can see that they are removed before the form is submitted
jsFiddle
HTML
<input id="test" type="text" value="Some Text" data-value="Some Text">
JS
$('#test').blur(function() {
el = $(this);
if (el.val() != el.attr('data-value')) {
console.log('Edited');
} else {
console.log('Not Edited');
}
});
I have the following code:
<form>
<input type="text" id="field1" name="field1" value="first value" />
<input type="text" id="field2" onkeyup="showRSS(this.value, this.alt)" value="" alt="test">
</form>
Within the showRSS() onkeyup function I need to call the value from the first input field (id="field1"). How can I do that?
Use its ID with document.getElementById():
So if you want to pass it as the third argument to showRSS():
<input type="text" id="field2" onkeyup="showRSS(this.value, this.alt, document.getElementById('field1').value)" value="" alt="test">
Or if you want to get it from within showRss():
function showRSS( ... )
{
var field1 = document.getElementById('field1').value;
}
If you want to get the values of specific text boxes you can just iterate them in the function and grab the value of those you want based on their name. First, add a name to the second textbox as well then have such code:
function showRSS() {
var oForm = document.forms[0]; //assuming only one form
var desiredInputNames = { "field1": "", "field2": "" }; //names of elements to read
for (var i = 0; i < oForm.elements.length; i++) {
var element = oForm.elements[i];
if (desiredInputNames[element.name]) {
var value = element.value;
//handle the current value
}
}
}
(Using associative array rather than plain array for better searching)
use the below code to do that...
<form>
<input type="text" id="field1" name="field1" value="first value" />
<input type="text" id="field2" onkeyup="showRSS(this.value, this.alt, this.parentNode.getElementsByName('field1')[0].value)" value="" alt="test">
</form>
if you use field1 as name outside the form tag, it won't create any problem...
The problem: I have a page with many <input> fields (just say all are text fields)
I would like to have a button, when click on it, all input fields will become plaintext only.
e.g. <input type="text" value="123" /> becomes 123
and if I click on another button, the text will change back to
e.g. 123 becomes <input type="text" value="123" />
Is there an automatic way to scan for all the <input>s and change them all at once using javascript and jquery.
Thank you!
Edited
Seems you guys are getting the wrong idea.
Read what I have written again: e.g. <input type="text" value="123" /> becomes 123
I have value="123" already, why would I want to set the value again???
What I want is e.g.
<body><input type="text" value="123" /><input type="text" value="456" /></body> becomes <body>123456</body> and later <body>123456</body> back to <body><input type="text" value="123" /><input type="text" value="456" /></body>
Use this to go one way,
$('input').replaceWith(function(){
return $('<div />').text(this.value).addClass('plain-text');
});
and this to go the other.
$('.plain-text').replaceWith(function(){
return $('<input />').val($(this).text());
});
Check this link http://jsfiddle.net/Evmkf/2/
HTML:
<div id='divInput'>
<input type="text" value='123' />
<br/>
<input type="text" value='456' />
<br/>
<input type="text" value='789' />
</div>
<div id='plainText' style='display:none'></div>
<div>
<input type="button" id='btnPlain' value='Make It Plain' />
<input type="button" id='btnInput' value='Make It Text' />
</div>
Javascript:
$("#btnPlain").bind('click',function(){
$("#plainText").html('');
$("#divInput input[type=text]").each(function(index){
$("#plainText").append('<span>'+$(this).val()+'</span>');
$("#divInput").hide();
$("#plainText").show();
});
});
$("#btnInput").bind('click',function(){
$("#divInput").html('');
$("#plainText span").each(function(index){
$("#divInput").append('<input type="text" value="'+$(this).text()+'"/><br/>');
$("#plainText").hide();
$("#divInput").show();
});
});
Try this FIDDLE
$(function() {
var arr = [];
$('#btn').on('click', function() {
var $text = $('#inp input[type="text"]');
if( $text.length > 0){
$text.each(function(i) {
arr[i] = this.value;
});
$('#inp').html(arr.join());
}
else{
if(arr.length <= 0){
}
else{ // Add Inputs here
var html = '';
$.each(arr, function(i){
html += '<input type="text" value="' + arr[i]+ '"/>'
});
$('#inp').html(html);
}
}
});
});
You need to create a hidden element for each input, then use jquery to hide the input, show the hidden element and give it the inputs value.
<input type="text" value="123" id="input_1" />
<div id="div_1" style="display:none;"></div>
$("#div_1").html($("input_1").val());
$("#input_1").hide();
$("#div_1").show();