I'm trying to prep forms with multiple (dynamic) inputs to insert correctly via ajax.
Currently, using my php loop, I have 4 div/forms. Each form has a starting input, and upon clicking the moreItems_add button, it dynamically adds another input, up to 10 per form/div.
This works fine. But I added a variable and console.log to log the value of my hidden input though, which should be getting an ID (<?php echo $ticker['ticker'] ?>) for each form, but it's currently only logging '1'. So when I clicked the button in the first form it looked right, but when I click the others, it's still 1. I think this is because I don't have a unique ID on the hidden input?
How can I change the way I'm keeping track of the hidden input so that I can make an ajax call that will only make an insert on the inputs of the given form WITH the correct ticker ID?
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
To generate a unique id attribute you should append your ticker value from php to... the id attribute. Or if not the ticker value, at least something that makes it unique. But you don't really need to.
Since all your elements are wrapped in a form tag and are at the same level, you can find to which ticker corresponds the clicked button by finding the hidden input among its siblings:
var tickerID = $(this).siblings('input[name="tickerID"]').val();
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>
I've a some dynamic buttons and when I click on them they display the price inside the div with id="prezzo".
but now I need that, when I click on one of those buttons, they fill the hidden value field of the form with the same "data-prezzo".
Basically I want that even the form value is dynamic like the div with id="prezzo"
Is this possible?
$(document).ready(function() {
$("input[id^=service]").on("click", getCheck);
$(".event-hook-class").on("click",function(e) {
e.preventDefault();
$(".event-hook-class").removeClass("active");
$(this).addClass("active")
$("#prezzo").html($(this).data('prezzo') + ' €');
$("#form-prezzo").setAttribute("value", $(this).data('prezzo'));
$("#piano").html('piano: ' + $(this).data('piano'));
getCheck(); // will add this and the checkboxes
});
getCheck(); // initialise on page load
});
<?php
echo '<button type="button" class="event-hook-class simple-text piano" id="'.$id_appartamenti.'" data-prezzo="'.$prezzo_piano.'" data-piano="'.$piano.'">.$id_appartamenti.' <br> piano '.$piano.'<br> prezzo '.$prezzo_piano.' €</button><br>';
?>
<p class="paragraph" id="prezzo"> €</p>
<form>
<input type="hidden" value="" id="form-prezzo" data-name="prezzo">
</form>
and a form with this imput field
You can use val() to set the input's value:
$("#form-prezzo").val(prova)
And also you have a double id attribute in you hidden field which is invalid
if you are getting the value of a div or p tag you can get it using the following code.
$("#prezzo").text()
As you can see in the above image. I have set of radio buttons, shown as picture. My client wanted to see picture instead of radio buttons. What also he wants is when user click an image (radio button), the value of that button should get displayed in the textarea field below. So user can see the value of selected radio button and also he should be able to edit it before he click save.
So user see what he selected and he can can also type before save.
I am using Jquery for this. So when user click the radio button, I capture the value the text of what user clicked and save in variable. Than I set the value of textarea field to that variable.
All works but the problem is when user select something and type something, and than if he click another picture, the field does not clear.
Question:
How I can copy the clicked value of clicked image and show in field and also allow user to type and if he click another image the field should become clear.
Here is my code
HTML
<div class="text-center">
<h4>Select reason</h4>
<form id="timer-reason">
<div class="row">
<div class="col-md-12">
<?php
while ($row = mysqli_fetch_assoc($timer_reasons)) {
?>
<label class="select-reason" value="<?php echo $row['description_tmr']; ?>" id="<?php echo $row['id_tmr']; ?>">
<input type="hidden" id="reason-id" value="<?php echo $row['id_tmr']; ?>">
<input type="radio" name="ReasonSelect" value="<?php echo $row['description_tmr']; ?>" />
<img src="../../css/timer-reasons/<?php echo $row['image_tmr']; ?>" style="width:30%;" class="TimerReason">
</label>
<?php
}
?>
<div class="form-group">
<textarea class="form-control" id="reason" value="" rows="2"></textarea>
</div>
</div>
</div>
</div>
JQUERY
$('input:radio').click(function() {
var reasonvalue=$(this).attr("value");
$("#reason").text(reasonvalue);
});
This is due to how the browser displays textarea's value that is supplied by putting text between the opening / closing tags, setting innerText / textContent
<textarea>Value between tags</textarea>
And a value supplied by the value property.
<textarea id="reason"></textarea>
document.getElementById('reason').value = "Value by property";
You can set the innerText / textContent multiple times, but as soon as it gets a set value property, which also happens when the user starts typing, changing the innerText / textContent will no longer change the visible text shown. The actual property is changed though.
var reasonTextarea = document.getElementById('reason');
var tcBtn = document.getElementById('tcTest');
var tcBtn2 = document.getElementById('tcTest2');
var propBtn = document.getElementById('propTest');
tcBtn.addEventListener('click',function(){
reason.textContent = "textContent set";
});
tcBtn2.addEventListener('click',function(){
reason.textContent = "textContent set again";
});
propBtn.addEventListener('click',function(){
reason.value = "value property set, now try typing something and/or hitting the change by textContent button again.";
});
<textarea id="reason" rows=5 cols=40>Test value 1</textarea>
<button id="tcTest">Click to change value by textContent</button>
<button id="tcTest2">Click to change value by textContent again</button>
<button id="propTest">Click to change value by property</button>
And this is what is happening with your code, you use jQuery's .text() method which changes the textContent of the textarea. Which will work as long as you never set the value property or the user never types in the textarea.
To combat this you should change the value of the textarea by changing the value property instead of the textContent property.
jQuery('#reason').val('New value');
Try this:
$(function () {
$('[name=ReasonSelect]') // bind event on all inputs with name RadioSelect
.on('change', function() { // on a change execute the function
var v = $('[name=ReasonSelect]:checked'); // get the selected value
$("#reason").val( v ); // put the value in #reason.
});
});
Try Below code. It Should work
$('input[type=radio]').click(function() {
var reasonvalue = $(this).attr("value");
$("#reason").val(reasonvalue);
});
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
I have 4 groups of data that are tied to a click-bind event. I'm trying to add the value from a hidden field contained within each group to a paragraph later in the page, so that when the checkbox is clicked from one or more groups of data, the value from the hidden field displays within the paragraph area.
I'd also like to get it so that when the checkbox is unclicked, it removes the value from the paragraph, but for now I'm just trying to get the value to display when the checkbox is clicked.
Here's what I've tried:
This is the hidden field within the group of data that stores the value:
<input id="servicename_<?php echo $i;?>" name="servicename_<?php echo $i;?>"
type="hidden" value="<?php echo $service->PRODUCT;?>"></input>
This is the click-bind event:
$('input[id^=ckNow_]').each(function(){
$(this).bind('click',function(){
if($(this).prop('checked'))
{
var servicename = '#servicename_'+$(this).attr('value').split("_");
ServiceName += servicename;
$('#lblServiceName').append($(ServiceName));
EDIT to add the checkbox that is within each group:
<input type="checkbox" id="ckNow_<?php echo $i;?>" name="ckNow[<?php echo $i;?>]">
</input>
And then the paragraph text:
<p id="lblServiceName">Service Name
<input type="hidden" id="servicename" value="0"></input>
</p>
What am I doing wrong and how can I fix it? All responses are very appreciated and I'm completely open to any and all suggestions. Thank you.
Try
<p id="lblServiceName">Service Name
<span></span>
<input type="hidden" id="servicename" value="0"></input>
</p>
then
jQuery(function ($) {
var $checks = $('.group-data input[name^="ckNow["]').change(function () {
var vals = $checks.filter(':checked').map(function () {
return $(this).closest('.group-data').find('input[id^=servicename_]').val()
}).get();
$('#lblServiceName span').text(vals.join(', '))
})
})
Demo: Fiddle