Trouble with getting right value from html input using jquery - javascript

I have this at the end of my PHP file:
<script type="text/javascript>"
$("#id").on("click", "#otherId", function(e)
{
var html = "<input class='id' type='text' size='5' />";
var row = $(this).closest("#addoid").html(html);
row.find("input").focus();
row.find('input').change( function(e)
{
var value = $(this).val();
var fid = $("input#idName").val();
$.ajax({
type: "POST",
url: "page.php",
data: { entryId: fid, val: value }
})
.done(function( msg ) {
alter("data: " + msg);
});
});
</script>
</body>
The html is something like this:
<div id="id">
<div id="otherId">
<input id="idName" type="hidden" value="1234" />
<button type="button" id="otherId">Add</button>
</div>
<div id="otherId">
<input id="idName" type="hidden" value="1235" />
<button type="button" id="otherId">Add</button>
</div>
<div id="otherId">
<input id="idName" type="hidden" value="1236" />
<button type="button" id="otherId">Add</button>
</div>
</div>
I left the earlier jquery code out, but basically, when the Add button is pressed, it is changed to an input field, if the user puts an id into the input field, it will display a link (on blur) or go back to the add button if nothing is entered.
So far it is working, however
var fid = $("input#idName").val();
is taking the next id (instead of 1234, it is posting 1235).
I am new to jquery. I have searched around and tried several different things but I am getting nowhere.
Thanks.
ADDITION
To make this more clear, I have a table that is being populated with a foreach loop (using php) it is pulling records from a database.
looks something like this:
<div id="list">
<table>
<?php foreach ($data as $value):?>
<tr>
<td>
<div class="row">
<button class="add">Add</button>
<input class="hiddenId" type="hidden" name="hiddenName" value="<?php echo $value['id']?>" />
</div>
</td>
</tr>
<?php endforeach?>
</table>
</div>
Like I explained earlier, when the "Add" button is clicked, it turns into an input field.
On change (of the input field), I need the ajax to send a request containing the values of the two input fields.
The problem I am having is I am not able to get the correct value of the hidden input. jquery is grabbing a value from another row, not the correct row.
I can't seem to figure this out and have honestly tried many different ways, including some that would probably be considered unconventional.
Thanks for any help.

Please first rename input ids, since ID has to be unique.

Related

Javascript concat clearing input fields

function js() {
document.getElementById("example").innerHTML = document.getElementById("example").innerHTML+"<input type=\"text\" name=\"name\" />";
}
<div id="example">
<input type="text" name="name[]" />
</div>
<button type="button" onclick="js();">Click</button>
I have a form, which need variable number of input types.
<form action="" method="">
[...]
<div id="mezok">
<div id="input_id">
<input type="text" name="name" />
</div>
</div>
[...]
</form>
I add and remove further inputs (along with their divs!) via an ajax call. Javascript calls a php which generates a new input_id div, and then concatenates to the rest of the div id="mezok". Adding and removing inputs are fine as long as everything is empty. However, when I add a new div when there is something in the input, it clears the rest of the inputs.
document.getElementById("mezok").innerHTML = document.getElementById("mezok").innerHTML+http.responseText;
document.getElementById("mezok").innerHTML += http.responseText;
document.getElementById("mezok").innerHTML.concat(http.responseText);
(The last one is not working at all...)
TL;DR: concat input to input, values of inputs disappear. :'(
Don't use innerHTML. What you are doing is redrawing the entire container contents, deleting existent inputs and creating new inputs each time. My experience says that when you are accessing innerHTML, recheck your code as you are probably doing something weird.
What you have to do is to create inputs individually and append them to the container, without touching the rest of the inputs. Is like appending elements to an array.
This way the code is more self-explanatory, and better, is way more performant:
function js() {
var input = document.createElement("input"); // Create a new input element. Is like "<input>".
input.setAttribute("type", "text"); // Set the 'type' attribute to 'text'. Is like having '<input type="text">'
input.setAttribute("name", "name[]"); // Set the 'name' attribute to 'name[]'. Is like having '<input name="name[]">' but because you already have set the type, now is like having '<input type="text" name="name[]">'
document.getElementById("example").appendChild(input); // Push it to the container
}
<div id="example">
<input type="text" name="name[]" />
</div>
<button type="button" onclick="js();">Click</button>
The code below could be a solution for you. In this way you're not going to overwrite the existing inputs with the associated values while you're adding new inputs.
function js() {
var inputElementToAppend = document.createElement('input');
inputElementToAppend.innerHTML = "<input type=\"text\" name=\"name\" />";
document.getElementById("example").appendChild(inputElementToAppend.firstChild);
}
<div id="example">
<input type="text" name="name[]" />
</div>
<button type="button" onclick="js();">Click</button>
Let me know if this worked for you.
Following working fine for me.
<button onclick="myFunction()">Try it</button>
<p id="demo">ABC</p>
<script>
function myFunction() {
var x = document.getElementById("myP").innerHTML;
document.getElementById("demo").innerHTML += `<input type=\"text\" name=\"name\" />`;
}
<script>
I would recommend to use appendChild and removeChild instead of innerHTML

Use JQuery to copy value from table to modal

I have a table with a list of all my data. The data is printed in a for loop so there are many rows in the table. how can i get the userid in the row with the button clicked?
<table>
<td>
<input type="hidden" value="<c:out value="${user.id}" />" name="userId" />
</td>
<td>
<button class="btn btn-default fileUpload" data-toggle="modal" id="btnUpload" data-target="#file-modal" value="<c:out value="${user.id}" />">Upload</button></td>
</table>
and i have a modal container. When the upload button in the table is clicked, the modal will open up for a file upload.
<form action="${pageContext.request.contextPath}/UserServlet" enctype="multipart/form-data" method="post">
<input type="hidden" value="5519" name="OPS" />
<input type="hidden" name="uploadUserId" />
<div class="form-group">
File : <input type="file" class="file" name="uploadFile"><br />
<button type="submit" class="btn btn-default">Upload</button>
<br /><br />
</div>
</form>
What i am trying to do is on the click of btnUpload the value in the hidden input type userId will be copied over to the hidden value type uploadUserId
I have tried doing the following but neither works
1
$(document).ready(function () {
$("#btnUpload").click(function(){
var $userId = $(this).closest("tr").find("#userId").text();
$("#uploadUserId").val($userId);
});
});
2
$(document).ready(function () {
$("#btnUpload").click(function(){
var $userId = $(this).closest("tr").children()[2].text();
$("#uploadUserId").val($userId);
});
});
This will do the trick without changing the html
$(document).ready(function () {
$("#btnUpload").click(function(){
var $userId = $(this).parent().prev("td").children("input:hidden").val();
$("#uploadUserId").val($userId);
});
});
Another solution by adding ID to the input element as shown below,
<input id="userVal" type="hidden" value="<c:out value="${user.id}" />"name="userId" />
then you can get the value from the following jquery
$("#userVal").val();
This should work. Just select and grab the user Id txt and then pass it to the uploadUserId value.
$(document).ready(function () {
$("#btnUpload").click(function(){
var $userId = $('#userId').text();
//$("#uploadUserId").val($userId);
$('input[name="uploadUserId"]').val($userId);
});
});
UPDATE
OK. I reviewed this again using your HTML structure and got this all worked out. The code below works.
$('[type="submit"]').on('click', function(e){
e.preventDefault(); // prevents the button default action. You can remove this if you want the form to submit after click.
var $userId = $(this).prev().prev().val(), // this gets the input value. based on your html it is the previous previous element.
fix1 = $userId.replace(/(?:\..+)$/, '').split('\\'), // this is a regex that replces the file extention then splits the string on the back slash turning it into an array.
fix2 = fix1.length -1; // gets the length of the array and subtracts 1 to get the last array index of the array. This i to get the file name.
$('[name="uploadUserId"').val(fix1[fix2]); // this assigns the uploadUserId value to the name of the file using the array and the index.
});

Input Text Box Returns Undefined in Javascript

Here is my HTML:
<form name='cred' class="panel-body2">
<div class="form-group">
<label for='addjidlbl'> Username (JID):</label>
<input type='text' id='addjid' />
</div>
<input type='button' id='add' value='add' />
</form>
Here is the JavaScript:
$('#add').bind('click', function() {
var jid = $('#addjid').value;
alert(jid);
//var jid=document.getElementById('addjid').value;
var jid2 =$('#addjid').get(0).value;
alert(jid2);
// //$('#addjid').get(0).value;
log('jid=>'+jid);
var data = document.getElementById("addjid").value; //$(".panel.panel-default2#addjid").value;
alert(data);
alert("type=>"+ typeof(jid));
addRoster(jid);
});
function addRoster(jid) {
log('addRoster=>' + jid);
}
What I get are two message boxes with "undefined" and third with "type=>undefined". Why can't I get the input text of the addjid text box?
If I change var jid = $('#addjid').get(0).value;, jid is just blank even when the textbox has value. Why?
Change .value to .val() like
$('#addjid').value
should be
$('#addjid').val()
Here you have it working using .val()
add some text to the text box and
click on the add button and the alert will popup
$('#add').on('click', function() {
alert($('#addjid').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='cred' class="panel-body2">
<div class="form-group">
<label for='addjidlbl'> Username (JID):</label>
<input type='text' id='addjid' />
</div>
<input type='button' id='add' value='add' />
</form>
If I understand correctly, you want:
$('#addjid').val()
Since you are using id's to get the value you will only have one element with the given id. When you do .get(0) or any index you are typically trying to get the value out of a given array of values. For Ex
<li>first</li> //0
<li>second</li> //1
Here in a structure like this you will do something like
$("li").get(0)
It will give you the first item with in li.
and to get the value you will need to use .val()
So you can use
$('#addjid').val()
Hope this helps you.
Happy Learning :)

POST DATA issues when adding new elements to the page

Hi all I have a form in which I dynamically add in a new row consisting of a text box and check button on button press. However I need some sort of way to know which checkbuttons were pressed in the post data and therefore need a value field consisting of an ID on each of the the check buttons, code is seen below:
<div id='1'>
<div class="template">
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
JS to add new row:
var $template = $('.template');
$('input[type=button]').click(function() {
$template.clone().insertAfter($template);
});
can anyone suggest a good way to help me know in the post data which text field, links to which check button, and to know if it was pressed?
at the moment if you were to add 3 rows and check row 3 I have no way of identifying that row three was the button pressed - This is my issue
after you cloned it, change the name so you know about this input
also it's good to have a counter for naming:
like : 'somename[myInput' + counter + ']'
update:
var counter = 0;
var $template = $('.template');
$('input[type=button]').click(function() {
counter++;
$template.clone().attr('name' , 'somename[myInput' + counter + ']').insertAfter($template);
});
now you have array named:somename which you can have a loop over its content on your form handler.

Submit multiple inputs through one form and append to array

So I am relatively new to JavaScript but I have experience with programming. I have this code which allows the user to define how many addresses they would like to enter so then I can query google maps and find the geographic center. The problem with this is that it looks very unprofessional in the sense that they have to enter the number of fields on one page and then they are prompted with that many boxes on the next page. Is there any way to make only one form(with all the parameters I require for one entry) and then after they click submit, I append it to an array and then when they decide they have enough addresses they hit the final submit so then I can process the data using a PHP call? Any help would be great, but I am new to this so I might need more spelt out explanations, sorry. Thanks again!
TL;DR: I want to create a single entry field which when submit is clicked, the page does not refresh or redirect to a new page and appends the data entry to an array. From there the user can enter a new input and this input would also be appended to the array until the user has decided no more inputs are necessary at which point they would click the final submit allowing me to process the data.
Here is the code I have so far:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function(){
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=0;i<c;i++){
$("#mydiv").append('<input type="text" id="data'+i+'" name="data'+i+'" /><br/>');
}
});
$("#button2").click(function(){
$.post("getdata.php",$("#form1").serialize(),function(data){
});
});
});
</script>
</head>
<body>
<form id="form1">
Type the number of inputs:
<input type="text" id="inputs" name="inputs" />
<input type="button" id="button1" value="Create" />
<div id="mydiv"></div>
<input type="button" id ="button2" value="Send" />
</form>
</body>
</html>
getdata.php
<?php
for( $i=0; $i<$_POST["inputs"] ; $i++){
echo $_POST["data".$i]."\n";
}
?>
Here is code:
EDIT: I rewrite the code, so you can also delete each address
$(document).ready(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']">Address ' + (numberOfAddresses + 1) + '</label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" />';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post">
<div class="address">
<label for="data[address][0]">Address 1</label>
<input type="text" name="data[address][0]" id="data[address][0]" />
</div>
<button id="add-address">Add address</button>
<br />
<input type="submit" value="Submit" />
</form>
After form submit you can loop through addresses like this:
foreach ($_POST['data']['address'] as $address){
...your code
}
Hope this help! :)
Normally how I do this kind of stuff is to provide a user ability to add many input fields at client level and send them all in one array when submitting the form. That is more professional I believe. Try this JSFiddle to see what I mean.
<input type="text" name="address[]" />
if you want to POST dynamic value in a form you can do it like this:
<input type="text" name="adress[]" />
so in your case you could add new fields with javascript or jquery with the same name name="adress[]".
and in your PHP you get an array:
$adresses= $_POST['adress'];
foreach ($adresses as $adress) {
echo $adress;
}
FIDDLE DEMO
To process an array of inputs you can use the following convention:
HTML: simply add square brackets to the name attribute
<input type="text" id="data'+i+'" name="data[]" />
PHP: Post returns an array
for( $i=0; $i<$_POST["data"] ; $i++){
echo $_POST["data"][$i]."\n";
}
JAVASCRIPT: $("#form1").serialize() will retrieve all the inputs data as name=value pairs even the inputs that are added dynamically. There's no need to keep an array you can just process all of them at the end.
You don't need to create an array, $_POST is actually doing it all for you already.
So I suggest you do the following: using javascript (or jQuery), keep the button clicks, but make sure the form submission is prevented (using preventDefault on the form) [EDIT: You actually won't need this, as if the buttons are just buttons, no submit inputs, the form will not submit anyway], and just make sure you append another element every time they click a plus button or something; make sure you increment the name attributes of each input element that gets created.
When the user then creates submit, use submit the form via js, then on your getdata.php you can simply loop through all the values and use them that way you want. You will even be able to know the exact number by calculating the number of times a new input element has been added to the form.
I'll try to write up something for you in a minute, but if I was clear enough, you should be able to do that too.
EDITED: So here is what I've come up with; give it a try and see if this is something for you.
This is how the form would look like:
<form id="form1" name="myform" method="post" action="getdata.php">
Enter address 1: <input type="text" name="address-1" /> <input type="button" value="More" onclick="createNew()" />
<div id="mydiv"></div>
<input type="submit" value="Send" />
</form>
And this would be the js code:
var i = 2;
function createNew() {
$("#mydiv").append('Enter address ' + i +': <input type="text" name="address-' + i +'" /> <input type="button" value="More" onclick="createNew()" /><br />');
i++;
}
...and then getdata.php:
foreach ($_POST as $key => $value) {
echo 'The value for '.$key.' is: '.$value.'<br />';
}
here is a fiddle demo

Categories

Resources