I'm trying to add/remove items dynamically but I can't take the values of all the elements of the array.
Basically I have this form
<form action="" method="post">
<div class="input_fields_wrap">
<div>
<label> <span>Team name </span>
<input type="text" class="input-field" name="teams[]"> </label>
</div>
</div>
<span id="num_teams"></span> <label><span> </span>
<input type="submit" value="Add Team" class="add_field_button" name="add_field_button">
<input type="submit" name="next" value="Next" />
</label>
</form>
It just shows an input box where I'd have to insert the team name and two buttons ; one to go to the next page, and the other one to add a new text field using jquery.
Here it is the jquery script
<script type="text/javascript">
$(document).ready(function() {
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
var max_fields = $('#n_teams').val(); //maximum input boxes allowed
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><label><span>Team Name </span><input type="text" class="input-field" name="teams[]"> Delete</label></div>'); // add input box
$("#num_teams").html('Number of Teams: '+x);
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('label').remove(); x--;
$("#num_teams").html('Number of Teams: '+x);
})
});
</script>
The script above works perfectly: it adds and removes textfields.
The problem that I have now is that I can't take the values of the array 'teams[]' .
in a
if(isset($_POST['next']))
even if I try to take the values manually like
echo $_POST["teams"][0]; and
echo $_POST["teams"][1]; ect...
It just takes the first value (i.e. the one I don't add using jquery). It doesn't 'see' the jquery text fields added.
Of course my final aim is to insert 'teams[]' in a mysql table, but for now I noticed that I can't either take the values.
Where am I wrong ?
EDIT - SOLVED
It was a very stupid error I made in the html code. Actually there was a <div> before of the <form> that caused all the troubles. After a very accurate analysis , trying every single piece of code alone, I finally got that I just had to move the <form> above two <div> to make the code work.
I do apologize to everyone, silly me!
Instead of using name="teams[]" use name="teams" and on server side use:
$_POST['teams']
which should give you the comma separated list.
var wrapper = $(".input_fields_wrap").first();
Related
I have a form in my input.html page and I have a set of input fields that is both programmatically generated by jinja2 and dynamically generated with Javascript. The inputs that are generated by jinja2 all show up in my request.form when I hit submit (i.e. into my POST function), but the dynamically created fields (with the + button next to a given element) aren't showing up. Which is strange, because if I inspect the page after adding a few new inputs, they... should?
Any ideas?
HTML
(explanation: this iterates through a ~dict and x has two text fields called question and tech-key (ex// "int"). This should print out the question with a 'plus sign' to allow the user to add new input fields dynamically. I include one by default (ex// name="{{x['tech_key']}}1" means name="int1". Every new input field that gets added increments (int1, int2, int3, etc...)
<div class="col-md-9">
{% for k,v in inps['sheet'].items() %}
{% for x in v %}
<div class="{{x['tech_key']}}">
<b>{{x['question']}}</b>
<button class="add_form_field" data-key="{{x['tech_key']}}"><b>+</b></button><br>
<div><input type="text" name="{{x['tech_key']}}1" size="80px"></div>
</div>
{% endfor %}
{% endfor %}
</div><br>
JavaScript
(explanation: This allows me for each individual named div (ex: the <div class="int"> above), to add new input fields when I click the + sign next to my product. I have them connected to the original form. They aren't pushing when I hit submit.
// adds new input fields when the + is clicked on a given question
$(document).ready(function() {
var max_fields = 10;
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e){
use = $(this).attr("data-key")
var wrapper = "."+use
e.preventDefault();
if(x < max_fields){
x++;
var field_name = use + x
$(wrapper).append('<div><br><input type="text" form="input_form" name="'+field_name+'"/ size=80px><a class="'+field_name+'"><button><b>-</b></button></a></div>'); //add input box
}
$("."+field_name).click(function(){
$(this).closest('div').remove(); x--;
})
});
});
HTML copied directly from my page when I add two new input fields:
<div class="int">
<b>Did you conduct any interviews this quarter?</b>
<button class="add_form_field" data-key="int" data-ol-has-click-handler=""><b>+</b></button>
<div>
<br><input type="text" name="int1" size="80px">
</div>
<div>
<br><input type="text" form="input_form" name="int2" size="80px">
<a class="int2"><button><b>-</b></button></a>
</div>
<div>
<br><input type="text" form="input_form" name="int3" size="80px">
<a class="int3"><button><b>-</b></button></a>
</div>
</div>
I'm building a simple tagging system for an text input field, here's what it looks like.
At the moment, the next tag is being added before the input field, but I'd like it to appear within the input field, so that if the users hits backsapce, it will delete the tag. If that makes sense. I'm not sure how to get the span to appear inside of the input field, here's the code:
<div id="formWrapper" class="ui-widget">
<form id="searchForm" action="#">
<fieldset>
<legend>Test search form</legend>
<span>Search</span>
<div id="searchBoxDiv" class="ui-helper-clearfix">
<button type="button" id="savedSearchButton">Test</button>
<input id="searchBox" type="text" autocomplete="false">
</div>
</fieldset>
</form>
</div>
function addSearchTerm(e, ui) {
var searchTerm = ui.item.value;
var span = $("<span>").text(searchTerm);
var a = $("<a>").addClass("remove").addClass("testclass").attr({
href: "javascript:",
title: "Remove " + searchTerm
}).text("x").appendTo(span);
span.insertBefore("#searchBox");
}
I've tried various combinations of insert, append but I don't seem to be able to get anything inside of the input, except text. I'm guessing I'll have to do something where the input field is within another , but I'm really not sure how.
Thanks
I would like to clear a text box when a radio button above the text box is selected.
I have tried this:
function clearThis(target){
target = document.getElementById(target);
target.value = "";
}
<input type="radio" name="not_req" id="clear_req" value=""
title="Click here to clear the No Auth need flag"><span id="clear" onclick = 'clearThis("claims")' >Clear
The box I would like to clear is
<input type="text" size="5" name="auth_for" id="claims" value="{$prior_auth->get_auth_for()}" title="Set the number of times no auth can be used">
Took most of this from http://jsfiddle.net/BMrUb/ but I can see that the example is clearing the adjacent text box. I would like to clear a text box not adjacent to the radio button.
As Gerald said place your onclick="" in the <input type="radio" ... >, not in the <span>.
The problem is that it's the sibling input element that needs its value clearing, not the span, even though you only want it to clear when people click on the span element. So the example code below does this. You're also best off decoupling your javascript from your HTML by using event listeners (and not using the old-fashioned onclick attribute).
var clearSpanEl = document.getElementById("clear");
clearSpanEl.addEventListener("click", function(e) {
var inputEl = e.target.previousElementSibling;
inputEl.value = "";
}, false);
<input type="text" name="search" id="search" value="I can be cleared" />
<span id="clear">Clear results</span>
I've forked your JSFiddle here, so you can see it working.
I am programming a web application which accepts barcodes from a barcode reader in an input field. The user can enter as many barcodes that s/he wants to (i.e. there is no reason for a predefined limit). I have come up with a brute force method which creates a predefined number of hidden input fields and then reveals the next one in sequence as each barcode is entered. Here is the code to do this:
<form id="barcode1" name="barcode" method="Post" action="#">
<div class="container">
<label for="S1">Barcode 1   </label>
<input id="S1" class="bcode" type="text" name="S1" onchange="packFunction()" autofocus/>
<label for="S2" hidden = "hidden">Barcode 2   </label>
<input id="S2" class="bcode" type="text" hidden = "hidden" name="S2" onchange="packFunction()" />
<label for="S3" hidden = "hidden">Barcode 3   </label>
<input id="S3" class="bcode" type="text" hidden = "hidden" name="S3" onchange="packFunction()" />
<label for="S4" hidden = "hidden">Barcode 4   </label>
<input id="S4" class="bcode" type="text" hidden = "hidden" name="S4" onchange="packFunction()" />
<label for="S5" hidden = "hidden">Barcode 5   </label>
<input id="S5" class="bcode" type="text" hidden = "hidden" name="S5" onchange="packFunction()" />
</div>
<div class="submit">
<p><input type="submit" name="Submit" value="Submit"></p>
</div>
</form>
<script>
$(function() {
$('#barcode1').find('.bcode').keypress(function(e){
// to prevent 'enter' from submitting the form
if ( e.which == 13 )
{
$(this).next('label').removeAttr('hidden')
$(this).next('label').next('.bcode').removeAttr('hidden').focus();
return false;
}
});
});
</script>
This seems to be an inelegant solution. It would seem to be better to create a new input field after each barcode has been entered. I have tried creating new input elements in the DOM using jQuery, and I can get the new input element to show. But it uses the onchange event, which detects changes in the original input field. How do I transfer focus and detect onchange in the newly created input field? Here is the code that I have played with to test out the idea:
<div>
<input type="text" id="barcode" class="original"/>
</div>
<div id="display">
<div>Placeholder text</div>
</div>
<script src="./Scripts/jquery-2.2.0.min.js"></script>
$(function () {
$('#barcode').on('change', function () {
$('#display').append('<input id='bcode' class='bcode' type='text' name='S1' autofocus/>')
});
});
</script>
Once I have these barcodes, I pack them into array which I then post them to a server-side script to run a mySQL query to retrieve data based on the barcodes, and then post that back to the client. So part of what I have to achieve is that each barcode that is entered into the different input fields need to be pushed into an array.
Is there an elegant way to accomplish the creation of input fields dynamically and then detecting changes in those to create yet more input fields?
The dynamic update you have tried out is all right. If you must push it into an array on submit you have to prevent default of form submit, serialize the form and then make an ajax request.
Heres an example:
$('form').on('submit',function(e){
e.preventDefault();
var formData = $(this).serializeArray();//check documentation https://api.jquery.com/serializeArray/ for more details
$.ajax({
type:'post',
url:<your url>//or you could do $('form').attr('action')
data:formData,
success:function(){}//etc
})
});
If you do not display the barcodes in the html you can skip the input fields and store the read barcodes in an array[]. Not everything that happens in javascript has to be displayed in the website (View) . i do not know what code you use to scan the barcode but you do not need the input-elements at all.
See the example on this site https://coderwall.com/p/s0i_xg/using-barcode-scanner-with-jquery
instead of console.log() the data from the barcode scanner can simply be saved in an array[] and be send from there.
If you want to create elements dynamcially see this thread: dynamically create element using jquery
The following code adds the p-element with the label "Hej" to the div "#contentl1"
`$("<p />", { text: "Hej" }).appendTo("#contentl1");`
UPDATE: I added some simple CSS to make each input field display on its own line.
Here's one strategy:
Listen for the enter/return key on the input box.
When the enter/return key is pressed (presumably after entering a barcode), create a new input box.
Stop listening for the enter key on the original input and start listening for it on the new input.
When a "submit all" button is pressed (or when tab is used to shift the focus from the most recent input to the "submit all" button and enter is pressed), then collect all the input values in an array.
$(function() {
var finishBarcode = function(evt) {
if (evt.which === 13) {
$(evt.target).off("keyup");
$("<input class='barcode' type='text'/>")
.appendTo("#barcodes")
.focus()
.on("keyup", finishBarcode);
}
};
var submitBarcodes = function(evt) {
var barcodesArr = $(".barcode").map(function() {
return $(this).val();
}).get();
$("#display").text("Entered Barcodes: " + barcodesArr);
};
var $focusedInput = $('.barcode').on("keyup", finishBarcode).focus();
var $button = $('#submitAll').on("click", submitBarcodes);
});
input.barcode {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Type barcode into input box</li>
<li>To enter barcode and allow new entry, press Return</li>
<li>To submit all barcodes, either press tab and then return or click Submit button</li>
</ul>
<div id="barcodes"><input type="text" class="barcode" /></div>
<div><button id="submitAll">Submit all barcodes</button></div>
<div id="display">Placeholder text</div>
Aloha, I'm trying to develop a slider bar that has 3 words that you can choose from. But I'm not able to save the words as letters, all I get is number either 1,2 or 3 :(
Here's the code I have and also a picture:)
<form action="something.php" method="post" id="form">
<input type="range" min=1 max=3 step=1 name="slider">
<div id="text">
<span > Bad </span>
<span> Ok </span>
<span> Good </span>
</div>
<input type="submit" value="next" id="but"/>
</input>
</form>
So this code shows the slider bar and letters at the top (which works with my css), but when I click "Submit", on the following page (using php) I get 1, 2 or 3.
But it should be Bad, Good or Good. I'm sure that the problem is in the HTML code.
Why not just assign the numerals to values when you process the submission?
if(isset($_POST['slider'])) {
$array[1] = 'Bad';
$array[2] = 'Ok';
$array[3] = 'Good';
// This is a simplified output, but this is essentially
// the easiest way
echo $array[$_POST['slider']];
}
There is two manner to do what you want :
1 - html + javascript :
You should add a hidden input in your form which before submitting your form you give it a value among the three : Bad, OK, Good according to the value of your slider.
2 - php :
<?php
$slider_index = intval($_POST['slider']);
$word = '';
switch ($slider_index) {
case 1:
$word = 'Bad';
break;
case 2:
$word = 'OK';
break;
case 3:
$word = 'Good';
break;
}
?>
This is not possible by using html only.
You could create a hidden input field and a "change" event handler on the range input field. The event handler sets the value of the hidden input field to the label corresponding to the selected number (1: bad, 2: ok, 3: good).
Example:
<form action="something.php" method="post" id="form">
<input type="range" min=1 max=3 step=1 name="slider" id="slider">
<input type="hidden" name="sliderLabel" id="sliderLabel" />
<div id="text">
<span > Bad </span>
<span> Ok </span>
<span> Good </span>
</div>
<input type="submit" value="next" id="but" />
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
(function() {
// function to update the value of the hidden field
updateSliderLabel = function() {
var selectedValue = $('#slider').val();
var selectedLabel = $('#text > span').eq(selectedValue-1).text();
$('#sliderLabel').val(selectedLabel);
}
// when slider is changed, call the update function
$('#slider').on('change', function() {
updateSliderLabel();
});
// when page is loaded, call the update function
updateSliderLabel();
})();
</script>
The advantage of this solution is, you can easily adopt your labels in the html code, you don't need to modify your php logic.