Jquery insert span into input field - javascript

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

Related

Replacing text on webpage

I want to take input of text by user which will replace a written text on webpage. just think i have a name in html, i have made form in which type his name and press (okay) after this, the name in tag replace by the name input by user and I have styled text by CSS written in tag.
//make sure the DOM is finished loading then execute our script
//by putting it in a ready function
$(document).ready(function() {
$('.ok').click(function(e) {
$('#result').addClass('sent'); // add styles to the submitted content
var nameVal = $('#nameField').val(); // get value in form field
//set the value of your div to form value
$('#result').addClass('sent').html(nameVal);
})
})
.sent {
// add custom styles here
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" class="form-control" id="nameField" placeholder="Jane Doe">
<input class="ok" type="button" value="Ok">
</form>
<div id="result">Value will be here</div>

Adding input elements to the DOM using jQuery

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 &nbsp </label>
<input id="S1" class="bcode" type="text" name="S1" onchange="packFunction()" autofocus/>
<label for="S2" hidden = "hidden">Barcode 2 &nbsp </label>
<input id="S2" class="bcode" type="text" hidden = "hidden" name="S2" onchange="packFunction()" />
<label for="S3" hidden = "hidden">Barcode 3 &nbsp </label>
<input id="S3" class="bcode" type="text" hidden = "hidden" name="S3" onchange="packFunction()" />
<label for="S4" hidden = "hidden">Barcode 4 &nbsp </label>
<input id="S4" class="bcode" type="text" hidden = "hidden" name="S4" onchange="packFunction()" />
<label for="S5" hidden = "hidden">Barcode 5 &nbsp </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>

Dynamic text field can't take the value jquery php

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();

retrieving text field value using javascript

I want to retrieve textfield value using javascript. suppose i have a code like:
<input type='text' name='txt'>
And I want to retrieve it using javascript. I call a function when a button is clicked:
<input type='button' onclick='retrieve(txt)'>
What coding will the retrieve function consist of?
You can do this:
Markup:
<input type="text" name="txt" id="txt"/>
<input type="button" onclick="retrieve('txt');"/>
JavaScript:
function retrieve(id) {
var txtbox = document.getElementById(id);
var value = txtbox.value;
}
Let's say you have an input on your page with an id of input1, like this:
<input type="text" id="input1" />
You first need to get the element, and if you know the Id, you can use document.getElementById('input1'). Then, just call .value to get the value of the input box:
var value = document.getElementById('input1').value;
Update
Based on your markup, I would suggest specifying an id for your text box. Incase you don't have control over the markup, you can use document.getElementsByName, like so:
var value = document.getElementsByName('txt')[0].value;
One of the way is already explained by Andrew Hare.
You can also do it by entering the value in the textbox and getting a prompt box with entered message when a user click the button.
Let's say, you have a textbox and a input button
<input type="text" name="myText" size="20" />
<input type="button" value="Alert Text" onclick="retrieve()" />
The function for retrieve()
function retrieve()
{
var text = document.simpleForm.myText.value;
alert(text);
}

Build URL from form fields with JavaScript or jQuery

I'm trying to create a URL builder form with JavaScript or jQuery.
Basically, it will take the value of the two form fields, add them to a preset URL and show it on a third field on submit.
The resulting URL might be http://example.com/index.php?variable1=12&variable2=56
Now, this isn't the "action" of the form and the application can't read a URL (to grab the variables), so it has to be done on the page.
The resulting URL will be shown in the field named "url".
Here's a sample of the form:
<form id="form1" name="form1" method="post" action="">
<p>
<label>Variable 1
<input type="text" name="variable1" id="variable1" />
</label>
</p>
<p>
<label>Variable 2
<input type="text" name="variable2" id="variable2" />
</label>
</p>
<p>
<label>URL
<input type="text" name="url" id="url" />
</label>
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>
jQuery has serialize which builds the query string values.
So if you want to do the entire form:
alert($("#form1").serialize());
If you want to do only a few fields, then just make the selector select those fields.
alert($("#variable1, #variable2").serialize());
Use something like...
var inputs = $('#form1').find('input[type=text]').not('#url');
var str = "http://www.base.url/path/file.ext?"
inputs.each(function (i, item) {
str += encodeURIComponent(item.name) + "=" + encodeURIComponent(item.value) + "&";
});
$('#url').val(str);
This will select all <input>s on in form1 with type='text', and concatenate them into a query string. See encodeURIComponent().
Orrrr.....you could just use .serialize(). Thank you, prodigitalson.
Something like the following should work:
var partFields = '#variable1,#variable2';
$(partFields).change(function(){
var url = 'static/URL/to/file.php?';
$('#url').val(url + $(partFields).serialize());
});
However, unless you want people to be able to override the URL, you might want to use a hidden field and a regular element for display and submission of the URL value in which case you'd have something like the following:
var partFields = '#variable1,#variable2';
$(partFields).change(function(){
var url = 'static/URL/to/file.php?';
var urlValue = url + $(partFields).serialize();
$('#url-display').text(urlValue); // Set the displaying element
$('#url').val(urlValue); // Set the hidden input value
});

Categories