I have the following code which I use to add text-boxes dynamically on click of button. It works.
<div id="forms" name="forms">
<input name="winner[]" type="text" id="tag" size="20"/><br/>
</div>
<input type="button" name="addmore" id="addmore" value="Add More Winners" onclick="addForm()"/>
The javascript for the above code is:
function addForm() {
$("#forms").append(
"<input type ='text' class='winner' name='winner[]'><br/>");
$(".winner").autocomplete("autocomplete.php", {
selectFirst: true
});
}
I am using auto complete to get data from database in the text-box
What I want is - suppose if a user clicks on add more winner button but does not want to add any data in the textbox, I should give him a button to delete the extra text-box.
How should the JavaScript be written for this?
Do see my above code
var i=0;
function addForm() {
i++;
$("#forms").append(
"<input type ='text' id='input_'"+i+" class='winner' name='winner[]'><button onclick='delete('"+i+"')' id='button_'"+i+">delete</button><br/>");
$(".winner").autocomplete("autocomplete.php", {
selectFirst: true
});
function delete(i)
{
$("#input_"+i).remove();
$("#button_"+i).remove();
}
simply use a counter to set an ID to inputs and buttons and send that counter to delete function;
Simply use the code below :
$("#forms").append("<p><input type ='text' class='winner' name='winner[]' ><button onclick='$(this).parent().remove()'>delete</button></p>");
Try this function.
function removeElement()
{
if(intTextBox != 0)
{
var contentID = document.getElementById('content');
contentID.removeChild(document.getElementById('strText'+intTextBox));
intTextBox = intTextBox-1;
}
}
Try adding a remove button while adding a text box dynamically to remove the text box if necessary
Here is the html code
<div id="forms" name="forms">
<input name="winner[]" type="text" id="tag" size="20"/><br/>
</div>
<input type="button" name="addmore" id="addmore" value="Add More Winners" />
Here is the jQuery code
$('#addmore').click(function () {
$('#forms').append('<input type ="text" class="winner" name="winner[]"><input type="button" onclick="$(this).prev().remove();$(this).remove();">');
});
Here is the demo
Related
I am trying to get respective values of dynamically generated inputs. In other words, I have an X number of dynamically generated inputs; each of these inputs is bound to a button. With that being said, I would like the user to get alerted the dynamically generated input that is bound to the clicked button. What I have done so far does not sort this out and whatever button is clicked, only the first input's value is generated.
I have the following code - a dynamic input and a button:
<input type="hidden" id="job_id" name="jobIdName" value="{{ job_id }}"> // please note this input is dynamically generated....
<button name="get_id_name" class="get_id_class" id="get_id_id" >Show Id</button>
As for Jquery, I have done the following:
$('#get_id_id').each(function(index) {
$(this).click(function() {
var job_ids = $("[name='jobIdName']");
console.log('Job Ids -------------- : ' + job_ids);
});
});
The above code keeps generating only the first generated input value? Any ideas or suggestions?
I have seen some posts that might seem similar to this one but they are very old; also I am looking for a more modern implementation.
Add your "input tag" into div:
var counter = 0;
$(document).ready(function(){
$("#get_id_id").click(function() {
var divChildren = $(".job_ids").children();
if(counter < divChildren.length){
if(counter == '0'){
console.log($(divChildren).eq(0).val());
}else{
console.log($(divChildren).eq(counter).val());
}
counter++;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class ="job_ids">
<input type="hidden" name="jobIdName" value="Test01">
<input type="hidden" name="jobIdName" value="Test02">
<input type="hidden" name="jobIdName" value="Test03">
<input type="hidden" name="jobIdName" value="Test04">
<input type="hidden" name="jobIdName" value="Test05">
</div>
<button name="get_id_name" class="get_id_class" id="get_id_id" >Show Id</button>
This works but then it disappears after like a second
function tfw() {
var TFW = document.getElementById("TFW").value
if (TFW == "mexicans") {
document.getElementById("image").innerHTML = "<h1>worked!</h1>";
event.preventDefault();
}
}
Occasion:
<input type="text" id ='TFW'><br>
<input type="submit" value="Submit" onclick="tfw();">
Change input type="submit" to input type="button" and also get rid of event.preventDefault() to fix the issue.
How to add multiple contact numbers within a single textbox and also a X(clear) button for each of the text added using javascript?
Below is a part of my HTML page
Contact No:<input type="text" id="no"><input type="button" value="ADD" id="add" onclick="javascript:addContact();">
<input type="text" id="text_name" style="width: 300px;height:50px;" />
Here is my javascript function
function addContact(){
var temp = document.createElement("input");
temp.innerHTML="<input type='search' value='' alt='clear' >";
var contact_added=document.getElementById("text_name").value;
var contact=document.getElementById("no").value;
document.getElementById("text_name").value=contact+temp+contact_added;
}
This is what I get as my output
![My output]
However what I need is that for every text that I enter,it should be follow by a clear so that I can clear that selected block of text
function addContact(){
temp="<input type='search' value=''. alt='clear' >";
var contact_added=document.getElementById("text_name").value;
var contact=document.getElementById("no").value;
document.getElementById("text_name").value=contact+temp+contact_added;
}
However this doesnt solve your problem. I think it isnt a good idea, doing this with inputs and buttons. This only makes it complicated.
At first make a form with a hidden field:
<form action="submit.php" method="post">
<input name="contacts" id="contacts_hidden" style="display:none">
</form>
<div id="contacts">
</div>
//your submit button and input
Now you can do:
contacts=[];
function addContact(){
newcontact=document.getElementById("no");
contacts.push(newcontact.value);
newcontact.value="";
render();
}
function delete(i){
contacts.splice(i,1);
render();
}
//this takes the contacts array and adds it to the page + hidden submit field
function render(){
hidden=document.getElementById("contacts_hidden");
all=document.getElementById("contacts");
content="";
for(i=0;i<contacts.length;i++){
//add a delete button
content+=contacts[i]+"<a href='javascript:delete("+i+")'>Delete</a>";
}
all.innerHTML=content;
hidden.value=contacts.join(";");
}
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.
});
$('#submit').click(function(){
$.post(
'/foo.php',{
name:myform.name.value,
interest:myform.interest.value,
interest2:myform.interest2.value...
}
});
<input type="button" value="Add more interest" />
I have a form use jquery post. There is a button can append more input type text.
My questions
1 when user click and append more input field, in side of $.post(... how can I add more script, so I can post it to next page?
2 in my php page
if(isset($_POST['interest1'], $_POST['interest2']...)){}
how can I know how many extra input fields user has added?
3 how can I limit maximum 3 input fields user can append?
Are you setting form fields manually in your post request?
Bad idea, you'd be better of using jQuery's serialize method:
$.post("/foo.php", $("#myForm" ).serialize() );
For your second question: use array naming on your form elements:
<input type="text" name="interest[]">
<input type="text" name="interest[]">
<input type="text" name="interest[]">
<input type="text" name="interest[]">
This way you get an array in your post array and can use it like so:
foreach ($_POST['interest'] as $interest) {
doStuff();
}
For your third question I'm assuming you wrote a JS method that
adds an input field to the form? If so you could implement
a limit this way:
window.formFieldCount = 1;
function addFormField() {
if (window.formFieldCount >= 3) {
alert('You can only add three interests!');
return false;
}
// Do your form magic here
window.formFieldCount++;
}
HTML:
<form name="some_name">
<div id="interests">
<input type="text" name="interests[]" />
</div>
<input id="more-interests" type="button" value="Add more interest" />
<input id="submit" type="button" value="Submit" />
</form>
Javascript:
$(document).ready(function(){
var maximumNumberOfInterests = 3;
$('#more-interests').click(function(e){
if ($("input[name='interests[]']").size() < maximumNumberOfInterests) {
$('#interests').append('<input type="text" name="interests[]" />');
} else {
alert('The maximum number of interests has been reached!');
}
});
$('#submit').click(function(){
$.post('/foo.php', $('form').serialize());
});
});
PHP:
if (count($_POST['interests'])) {
foreach ($_POST['interests'] as $interest) {
echo $interest;
}
}
Here is a DEMO of the HTML/Javascript part
q2. can you change form like this:
static inputs
<input name='static[something]'>
<input name='static[somebody]'>
<input name='static[etc]'>
and dynamically generated inputs
<input name='dynamic[]'>
<input name='dynamic[]'>
<input name='dynamic[]'>
php
if (isset($_POST['dynamic']))
{
foreach ($_POST['dynamic'] as $key => $value)
{
/* do some shit with dynamic inputs */
}
}
Please use prepend function before form submit
Like
$("#myForm").prepend("<input type=\"text\" name=\"interest"+counter+"\"").submit(function(){
console.log($("#myForm" ).serializeArray())
$.post(Event.target.action, $(Event.target).serializeArray(), function(data){
// your code here
})
return false;
})