I'm using Jquery in order to add dynamic inputs on my page. I only want to display one input initially, then more can be added by clicking a button.
This works as expected.
I'm then using PHP in order to catch the $_POST values of the inputs and send them to an external script. This also works, however I'm always receiving one extra item in my array, and it's empty.
I think this is because I have a hidden <div> field in my HTML, which is shown when a new input is generated?
My code is below;
HTML
// unnecessary code removed
<div class="after-add-more">
<button class="add-more" type="button" title="Add"></button>
<input name="addmore[]" value="" type="text">
</div>
<div class="copy-fields hide">
<div>
<button class="remove" type="button" title="Remove"></button>
<input type="text" name="addmore[]" value="">
</div>
</div>
JQUERY
$(document).ready(function() {
//here first get the contents of the div with name class copy-fields and add it to after "after-add-more" div class.
$(".add-more").click(function() {
var html = $(".copy-fields").html();
$(".after-add-more").after(html);
});
//here it will remove the current value of the remove button which has been pressed
$("body").on("click", ".remove", function() {
$(this).parents(".control-group").remove();
});
});
PHP
<?php
// unnecessary code removed
$field_values_array = $_POST['addmore'];
?>
Without generating an additional input, I enter 1111111 into the input box and submit. A print_r($_POST) produces;
[addmore] => Array
(
[0] => 1111111
[1] =>
)
Any help is appreciated.
You are probably better just getting the parent of the element that was clicked and adding your markup after that. Here is an example:
$(document).ready(function() {
// this function handles the click event
function addField(parent) {
// find your template, in this case its the first .after-add-more
var html = $(".after-add-more").first().clone();
// reset the value of any inputs
$('input', html).val('');
// wire the click handler for the button
$("button", html).click(function() {
addField($(this).parent());
});
// append it to the parent of the parent, addContainer
html.appendTo(parent.parent());
}
// wire the click handler for the add-more button
$(".add-more").click(function() {
addField($(this).parent());
});
// I don't know what the intention of this code is so I'm leaving it alone
$("body").on("click", ".remove", function() {
$(this).parents(".control-group").remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
// unnecessary code removed
<div id="addContainer">
<div class="after-add-more">
<button class="add-more" type="button" title="Add">Add</button>
<input name="addmore[]" value="" type="text">
</div>
</div>
<div class="copy-fields hide">
<div>
<button class="remove" type="button" title="Remove">Remove</button>
<input type="text" name="addmore[]" value="">
</div>
</div>
Related
So I have some buttons that will toggle some input text areas where I can send a message, how do I make it so when I click a button from a specific list, it only activates the button in that specific list.
I tried so many other things but I really don't know how to get this over it.
I'm kinda new to JS, I mainly do Java.
function showFeedback (list) {
var lines = "";
var counter = 0;
list.forEach(function (obiect) {
$(document).ready(function(){
$("button").click(function(){
$("#div"+ obiect.idfeedback +"").fadeToggle("slow");
});
});
counter++;
var style = "";
if(obiect.feedbackType == 1){
style = "style=\"background: green;\"";
} else if(obiect.feedbackType == 0){
style = "style=\"background: red;\"";
}
lines += `<div class="page-block"><div style="text-align: right">X</div><div class="cv-block" ${style} >
<div id="parent_div_1">
Name: ${obiect.firstn}
${obiect.lastn}
</div>
<div id="parent_div_2" style="float: right">
Date: ${obiect.date}
</div>
<div class="message_div"><p>${obiect.message}</p></div>
</div>
<button>Contact</button>
<div id="div`+ obiect.idfeedback +`" style="display: none">
<form action="contact" method="post">
<textarea name="message" id="umessage" cols="30" rows="10" maxlength="450" placeholder="Type your message here..." style="height:115px;width: 620px"></textarea>
<input type="hidden" name="email" id="umail" value="`+obiect.email+`">
<input type="hidden" name="action" value="feedback">
<div><input type="submit" value="Send Email"></div>
</form>
</div>
</div>`;
}); if(counter==0){
lines+= `<div class="page-block">No feedbacks to review.</div>`;
}
$("#obiect").html(lines);}
Get rid of $(document).ready, it is used to make sure the markup has been loaded before assigning events. In your scenario, markup is being generated dynamically, plus document.ready inside a loop does not make sense.
The simplest way to fix this code is to move the $('button') outside the loop. After the loop, do the following
$('button').click(function(){
$(this).next().fadeToggle("slow");
})
What this code does is add a handler on the click event of every button element, when the button's clicked, it finds the element which is placed next to the button element, which in your case is the required div element, and show that.
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.
});
In the markup, i have several divs with same id and inside those divs there are paragraphs and buttons. Now when a button is clicked, i want to get the value of a corresponding paragraph tag under the same div as that particular button. How can i do this with jQuery? The markup is as followed:
<div class="col-sm-5 narrow">
<p id="title">Jhon123</p>
<p id="text">This is the status of jhon</p>
<p>posted at 12:30pm GMT6+</p>
<form class="form-inline">
<input type="text" class="form-control" id="reply" placeholder="Type and enter to reply">
<button type="button" class="btn btn-default" id="repost">Re-Tweet</button>
</form>
</div>
When the button with the id #repost is clicked, i want to access the html inside the p tag with the id #text. I tried something like this:
$('#retweet').click(function(e){
e.stopPropagation();
var text = $(this).parent("div").closest('#text');
alert("some retweet button has been pressed which has the text:"+text);
});
You can use the jQuery .closest() function to get the containing <div> and then find the <p> tag you want inside it:
$('#repost').on('click', function () {
var text = $(this).closest('div[class^=col]').find('#text').html();
console.log(text);
});
The div[class^=col] selector means "find the closest div tag with a class starting with col". This allows you to use the other bootstrap column classes as well and have it still work.
$('#repost').click(function(){
console.log($(this).closest('div').find('#text').html());
});
See demo http://jsbin.com/wojupoyosa/1/edit?html,js,console,output
and as comments suggest you IDs should be unique per page so you should use a class or something else instead.
$( "#text" ).text() will give you the value inside P tag. So your code will look something like:
$('#repost').click(function(){
$( "#text" ).text() // save it to wherever you want
});
As a side note it is generally frowned upon to have css id's that are not unique - shared identifiers should use a class.
If you change all your ids into classes as shown in the demo below, then the following code should work fine. Also, you do not need the form element.
$('.repost').click(function(){
var text = $(this).closest('div').find('.text').text();
alert("some retweet button has been pressed which has the text: " + text);
});
$(function() {
$('.repost').click(function(){
var text = $(this).closest('div').find('.text').text();
alert("some retweet button has been pressed which has the text: " + text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-sm-5 narrow">
<p class="title">Jhon123</p>
<p class="text">This is the status of jhon</p>
<p>posted at 12:30pm GMT6+</p>
<form class="form-inline">
<input type="text" class="form-control reply" placeholder="Type and enter to reply">
<button type="button" class="btn btn-default repost">Re-Tweet</button>
</form>
</div>
<div class="col-sm-5 narrow">
<p class="title">Mary123</p>
<p class="text">This is the status of mary</p>
<p>posted at 12:35pm GMT6+</p>
<form class="form-inline">
<input type="text" class="form-control reply" placeholder="Type and enter to reply">
<button type="button" class="btn btn-default repost">Re-Tweet</button>
</form>
</div>
When I click on submit1 and then on submit2 everything is going well, but, when I press Enter Key on 1st input text I go to the second part
When I press Enter Key on the 2nd input text -> 1st JavaScript function executes which causes me trouble.
I don't want to disable Enter Key press, but that he executes the good submit input.
Is there a way to deactivate submit1 after he has been executed?
Or know from which input text Enter Key has been pressed?
HTML:
<div id="1">
<input type="text" placeholder="name"/>
</div>
<div id="2">
<input type="submit" value="submit" id="submit1"/>
</div>
<div id="3">
<input type="text" placeholder="firstname"/>
</div>
<div id="4">
<input type="submit" value="submit" id="submit2"/>
</div>
CSS:
#3, #4
{
display: none;
}
JavaScript:
$(document).ready(function() {
$("#submit1").click(function () {
/* Verify data with javascript and send it with Ajax */
/* if everything is ok display: */
document.querySelector("#2").style.display = "none";
document.querySelector("#3").style.display = "block";
document.querySelector("#4").style.display = "block";
});
$("#submit2").click(function () {
/* Verify data with javascript and send it with Ajax */
});
});
Unless I misunderstood the question - you are simply trying to make sure that the correct event handler gets called based on which button is selected by the user. This will work fine as long as the buttons have unique IDs which they do - and you can associate them with the correct event handler (which it seems like you are doing in the shared code).
Also, you can disable any button using the disabled attribute (set it to true).
to disable
document.getElementById("submit1").disabled = true;
to enable:
document.getElementById("submit1").disabled = false;
From what I can tell your biggest problem here is that you seem to have two submit buttons in a single form tag. I would seriously recommend against this as it can cause issues like the one you are experiencing. Instead I would change both to buttons and add the submit functionality to JavaScript methods as you are kind of doing now.
Obviously though you would want to link the text boxes to a button then and for that I would take a look at this SO question How to trigger HTML button when you press Enter in textbox?
<input type="submit"> is a special control. It will cause the form to submit if the form has focus and the enter button is pressed. When using this you should make use of event.preventDefault() to cancel that behavior when binding to the click event. I suggest using <button type="button"><button> instead.
If you press ENTER on submit1, submit2 will not be selected unless you hit TAB. Are you doing this?
Anyway, you can do this:
$("#submit1").click(function () {
/* Verify data with javascript and send it with Ajax */
/* if everything is ok display: */
$("#submit2").focus(); // This will automatically focus the user on the second submit button //
});
This will force the user, the next time he hits ENTER, to submit the submit2 button.
But don't use .submit()... you should use the .submit() function instead of .click(), because I believe .click() only checks for mouse clicks?
$("#submit1").submit(function(){
/* Blah blah blah... */
$("#submit2").focus(); // This will automatically focus the user on the second submit button //
});
$("#submit2").submit(function(){
/* ... */
});
As other users have said, are submit1 and submit2 in the same <form> tag:
Yes, they were. But you shouldn't have 2 fields in the same <form> tag if you want to submit the data separately.
Do this:
HTML
<form>
<div id="1">
<input type="text" placeholder="name"/>
</div>
<div id="2">
<input type="submit" value="submit" id="submit1"/>
</div>
</form>
<form>
<div id="3">
<input type="text" placeholder="firstname"/>
</div>
<div id="4">
<input type="submit" value="submit" id="submit2"/>
</div>
</form>
JQuery
$("#submit1").submit(function(e){
/* Blah blah blah... */
e.preventDefault(); // Keeps the user on the same page //
});
$("#submit2").submit(function(e){
/* ... */
e.preventDefault(); // Keeps the user on the same page //
});
I let it work like that:
Why should I have troubles with one form? IE < 6?
HTML:
<form>
<div id="1">
<input type="text" id="text1"/>
</div>
<div id="2">
<input type="submit" value="submit" id="submit1"/>
</div>
<div id="3">
<input type="text" id="text2"/>
</div>
<div id="4">
<input type="submit" value="submit" id="submit2"/>
</div>
</form>
CSS:
#3, #4
{
display: none;
}
JAVASCRIPT:
$(document).ready(function() {
$('#text2').keypress(function(e){
if(e.keyCode==13)
$('#submit2').click();
});
$("#submit1").click(function () {
/* Verify data with javascript and send it with Ajax */
/* if everything is ok display: */
document.querySelector("#2").style.display = "none";
document.querySelector("#3").style.display = "block";
document.querySelector("#4").style.display = "block";
document.querySelector("#submit1").disabled = true;
});
$("#submit2").click(function () {
/* Verify data with javascript and send it with Ajax */
});
});
I have a page with multiple divs that all look like the example below.
Each div contains a field, a hidden field and a button.
How can I achieve that by click on the button the (visible) input field gets triggered ?
I need to trigger either a click or focus as both fire the same function.
Each button in question has the class="triggerBtn" and the corresponding input field has the class="inputField".
Example div:
<div>
<input type="text" class="inputField" id="field1" name="field1" />
<input type="hidden" name="field1" />
<button type="button" class="btn btn-primary triggerBtn">Find</button>
</div>
I guess you want:
$(".triggerBtn").click(function () {
$(this).closest('div').find('.inputField').focus();
});
add
Onclick="function()" see here
if you need to trigger it manually using jquery you can to this by
$("#field1").trigger("click");
see also here
$(".triggerBtn").on("click",function(e){
$(this).closest("div").find(".inputField").click();
//or $(this).closest("div").find(".inputField").focus();
});
$(".triggerBtn").parent().children("input[type:text]").first().focus()
Updated Jsfiddle: http://jsfiddle.net/ZmL4y/3/
$(document).on("click",".triggerBtn", function() {
var inputField = $(this).closest('div').find('.inputField');
if($(inputField).is(":visible"))
{
$(inputField ).focus();
}
});