I need to grab the code from another part of my page without putting it in the form… is there a way to do it with JavaScript/jQuery?
Essentially, I’d like to take the value from here:
<div class='span5' style='margin-left:0px !important;'>
<label for='area0'>
<input type='checkbox' name='area' id='area' value='West Palm Beach' style='margin-top:-5px !important;'>
West Palm Beach
</label>
</div>
And put it into the form that exists elsewhere on the same page.
<form method="post" class="form-horizontal" id="final_form" action="send_mail.php">
MORE INPUTS
</form>
Is there a simple JavaScript way to do this? I just want to take the value if the checkbox is checked and assign it as a value within the form so that it gets passed on to send_mail.php.
You can add a hidden field inside the form, like:
<input type="hidden" id="area_is_checked" name="area_is_checked" />
Then use JQuery to get the checkbox value before submitting the form:
$("#final_form").submit(function () {
$("#area_is_checked").val($("#area").is(':checked'));
return true;
});
Sure!
$('form#new-location').append($("div#move-me-please"));
Here's a jsFiddle: http://jsfiddle.net/zwxPt/
Edit: since the answer was edited after I wrote this:
If you really can't add a hidden field to the form, you can still add extra data to your form when the user submits it by submitting it via ajax. See this stackoverflow question for more info.
You can use the form attribute (works in at least Opera 9.5+, Safari 5.1+, Firefox 4+, Chrome 10+):
<input type='checkbox' name='area' id='area' value='West Palm Beach' style='margin-top:-5px !important;' form="final_form">
There is a Modernizr test for it. You can however still use the form attribute, and then search for those instead of hard-coding the external inputs like the following:
$('#final_form').on('submit', function() {
$('input[form=' + this.id + ']').each(function() {
var externalInput = $(this);
// then same as below.
});
});
Or using jQuery instead of the form attribute:
$('#final_form').on('submit', function() {
var externalInput = $('#area');
var name = externalInput.attr('name');
/* use existing */
var hidden = $(this).find('input[name=' + name + ']');
/* create a new hidden field */
if ( ! hidden.length ) {
hidden = $('<input>', {
name: name
}).appendTo(this);
}
hidden.val(externalInput.is('[type=checkbox]') ? externalInput.prop('checked') : externalInput.val())
});
This will create a hidden field or, if you're doing validation on it and it might not actually submit, use one that was already added. This requires not update to the HTML.
Yes, there is..
<div id="inputsBlock" class='span5' style='margin-left:0px !important;'>
<label for='area0' style="display: none;">
<input type='checkbox' name='area' id='area' value='West Palm Beach' style='margin-top:-5px !important;'>
West Palm Beach
</label>
</div>
<form method="post" class="form-horizontal" id="final_form" action="send_mail.php">
MORE INPUTS
</form>
<script>
$('#inputsBlock').children().clone().css({display: 'none'}).appendTo($('#final_form'));
</script>
Related
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>
I'm trying to take some js that pulls data from another web application and populates a form by clicking "Populate Contact Info" and then click a "Submit" button to push the fields to a new php that then processes them. So basically how do I pass populated form field to a second form on the same page that I can then submit? Or is there a better way?
<form action="#" name="data" id="data">
<input type='button' value='Populate Contact Info' onclick='popAllContactFields()' />
Contact Info:
First Name: <input type='text' readonly="readonly" id='cfname' name='cfname' />
Last Name:<input type='text' readonly="readonly" id='clname' name='clname' />
Email: <input type='text' readonly="readonly" id='cemail' name='cemail' />
</form>
<script type="text/javascript">
/* popAllContactFields()
Populates all the contact fields from the current contact.
*/
function popAllContactFields()
{
var c = window.external.Contact;
{
// populate the contact info fields
popContact();
}
}
/* popContact()
Populates the contact info fields from the current contact.
*/
function popContact()
{
var c = window.external.Contact;
// set the contact fields
data.cfname.value = c.FirstName;
data.clname.value = c.LastName;
data.cemail.value = c.EmailAddr;
}
</script>
<form action="ordertest.php" method="post">
<input name="cfname" id="cfname" type="hidden" >
<input name="clname" id="clname" type="hidden" >
<input name="cemail" id="cemail" type="hidden" >
<input type="submit" value="Submit">
</form>
If you can manage to receive the data with an AJAX call as a JSON then it's vary easy. With using jQuery ($) and Lodash (_ but you can try Underscore as well):
$.get('an-url-that-returns-the-json', function(parsedData) {
_.forEach(_.keys(parsedData), function(key) {
console.log('key:', key);
$('#'+key).val(parsedData[key]);
});
});
If it's tough at first sight read some about jQuery selectors, AJAX ($.get()) and $(...).val().
You can also make a list about the keys that you want to copy, e.g. var keysToCopy = ['cfname', 'clname', 'cemail'] and then _.forEach(keysToCopy, function(key) {...}), this gives you more control with the copied data.
If you cannot use AJAX but can control the output of the source PHP, then I'd rather create the data as a raw JS object. If you cannot control the generated stuff then you must use something like you wrote, that also can be helped by some jQuery based magic, e.g.
_.forEach(keysToCopy, function(key) {
var prop = $('#source-form #'+key).val();
$('#target-form #'+key).val(prop)
});
Based on these you can think how you can solve if the source and target IDs are not the same.
I have a form with a bunch of checkboxes and input fields. I'm using jquery(1.10.1) to manipulate a number of things about the form based on user input from another form on the page. This was all working a few weeks ago but suddenly I've found that none of the checkboxes are submitting after they are changed by jquery.
The checkboxes are of the form:
<input type="checkbox" id="prod_70" name="prod[70]" class="product style_1 color_1 lens_3 status_1 " value="1" checked />
My Jquery code looks the other form to decide which boxes the user is interested in and then creates a selector based on that and the classes assigned to the checkboxes checking the boxes requested by the user:
$(curSel).prop('checked',true);
I was using:
$(curSel).attr('checked','checked').prop('checked',true);
But simplified since that shouldn't be necessary. I also tried adding a .change() for good measure but that didn't solve the problem so I took it back out.
When I submit the form none of the checked checkboxes show up and $_POST['prod'] (PHP on the backend) isn't there. $_REQUEST['prod'] is also not there. The other fields on the form are submitting. And if I submit the form without letting jquery update anything then the checkboxes do submit and $_POST['prod'] is as expected.
I've used the console in chrome and firebug in firefox to inspect the checkboxes while interacting with the page and 'checked' is being added and removed and the checkboxes are displaying correctly even when they're not submitting.
I've checked the HTML on the page to make sure everything is valid and there aren't any missing close tags or nested tags and the only other JS on the page are for FB's like button and twitters follow button.
I'm at a loss as to what could be causing this and my searches aren't turning up anything similar anymore.
EDITING TO ADD MORE:
After more debugging it appears that the problem isn't with changing the checkboxes. It's happening when the <li> that the checkboxes are in is hidden with .hide() and then reshown with .show(). After doing that the checkboxes in the <li> are never submitting even though other form elements inside the <li> are. Here's a full <li>:
<li class="prod style_1 color_1 lens_7 status_1 bulk-list-item" id="prod_55">
<div class="bulk-prod-name">
<input type="checkbox" id="prod_55" name="prod[55]" class="product style_1 color_1 lens_7 status_1 " value="1" />
<label for="prod_55">
<span class="style-name">Player</span>
<span class="color-name">Matte Black</span> |
<span class="lens-name">Rose Hi-Def LTD 17/35</span>
<span class="part-number">PLMBHD03</span>
<div style="margin-top:10px;">
<span class="bulk-prod-status">Status: <b>In Stock</b></span>
</div>
</label>
</div>
<div class="bulk-prod-image">
<div style="position:absolute; top:0;"><img style="width:100%;" src="/art/products/11/1/frame/thumb/1.png"></div>
<div style="position:absolute; top:0;"><img style="width:100%;" src="/art/products/11/1/lens/thumb/7.png"></div>
<div style="clear:both;"></div>
</div>
<div class="bulk-prod-price">
MSRP: $ <input type="text" id="prod_msrp_55" name="prod_msrp[55]" class="msrp inputbox" value="179.00" prod_id="55">
<input type="hidden" id="prod_msrp_orig_55" class="orig_price" value="179.00" orig_id="prod_msrp_55">
Dealer Price: $ <input type="text" id="prod_dprice_55" name="prod_dprice[55]" class="dprice inputbox" value="90.00" prod_id="55">
<input type="hidden" id="prod_dprice_orig_55" class="orig_price" value="90.00" orig_id="prod_dprice_55">
</div>
<div class="bulk-prod-edit">
Edit this product.
<div style="display:none" id="files_55">
<table width=100%>
<tr>
<td width=50% valign=top><small>Fullsize:<br>
<span style="color:#009900"> /art/products/11/1/frame/full/1.png</span><br>
<span style="color:#009900"> /art/products/11/1/lens/full/7.png</span><br>
</small>
</td>
<td width=50% valign=top><small>Thumbnais:<br>
<span style="color:#009900"> /art/products/11/1/frame/thumb/1.png</span><br>
<span style="color:#009900"> /art/products/11/1/lens/thumb/7.png</span><br>
</small>
</td>
</tr>
</table>
</div>
</div>
</li>
And here's the full jQuery that's hiding/showing/checking/unchecking things:
$(document).on('change', '.prod_selector', function(e) {
// console.log('Selection changed:');
e.preventDefault();
$('.prod').hide();
$('.product').prop('checked', false);
var lens = $('#lens_selector').val();
var color = $('#color_selector').val();
var style = $('#style_selector').val();
var pstatus = $('#status_selector').val();
var curSel = '';
if (lens>0) {
curSel += '.lens_' + lens;
}
if (color>0) {
curSel += '.color_' + color;
}
if (style>0) {
curSel += '.style_' + style;
}
if (pstatus>0) {
curSel += '.status_' + pstatus;
}
if ((lens==0) && (color==0) && (style==0) && (pstatus==0)) {
curSel = '.prod';
$('.product').prop('checked',true);
}
// console.log('curSel: ' + curSel);
$(curSel).show()
$(curSel).prop('checked',true);
$('#prod_count').text($('.prod:visible').length);
});
After messing with things I've determined that if I don't .hide() anything then it all work as expected (other than not hiding things that need to be hidden) but if any <li>'s are hidden then even once their shown again checkboxes inside of them don't get included in the form submission even though other input fields do.
I see a semi-colon missing:
$(curSel).show()
$(curSel).prop('checked',true);
The missing semicolon can stop the second statement from setting any checkbox as checked.
Problem solved. Turns out I was asking the wrong question. After more testing I finally determined that it wasn't jquery causing the problem after all.
The problem was more items were added to the database that this page manages which added more fields to the form and we were hitting the max_input_vars limit in the php config. Which I realized could be causing the issue after finding this: Limit of POST arguments in html or php
I raised the max_input_vars for this site and now the form is working again.
As you know I want to remove default value of a text box while clicking on it, This code works.
But when I click on the box and then click again another part of screen (I mean out of textbox) the data won't come back.
what should I do?
<html><head><title>(Type a title for your page here)</title>
<script type="text/javascript">
function make_blank()
{
document.form1.type.value ="";
}
</script>
</head>
<body >
<form name=form1 method=post action='test.php'>
<input type=text name=type value='Enter your user id' onclick="make_blank();">Enter User ID
<b>Type</b>
<input type=submit value=Submit> </form>
</body>
</html>
The solution to your problem is one of the following, depending on whether you're using HTML5 or XHTML (or HTML4). Since you're not stating which one you're using, I'll add both.
By the way, you really want to use the focus event, and not the click event. This is because a user can also navigate to a form field using his/her keyboard or by other access keys.
As Quentin correctly states, the specification is clear about what a placeholder text is supposed to be used for. Therefore I've updated the text you're using to something more fitting.
HTML5
<input type="text" name="type" placeholder="email#example.com">
XHTML
HTML:
<input type="text" name="type" value="email#example.com"
onfocus="make_blank(this);" onblur="restore_placeholder(this);" />
Javascript:
function make_blank (oInput)
{
if (!('placeholder' in oInput))
oInput.placeholder = oInput.value;
if (oInput.value != oInput.placeholder)
oInput.value = '';
}
function restore_placeholder (oInput)
{
if (oInput.value == '' && 'placeholder' in oInput)
oInput.value = oInput.placeHolder;
}
The following combination of HTML5 and JavaScript (for HTML4) works nice for me:
HTML:
<input type="text" name="type" placeholder="email#example.com"
onfocus="make_blank(this);"
onblur="restore_placeholder(this);" />
Javascript:
function make_blank(oInput) {
if (oInput.value == 'placeholder') {
oInput.value = '';
}
}
function restore_placeholder(oInput) {
if (oInput.value == '') {
oInput.value = 'placeholder';
}
}
I want to add "i" to a input field when the red div is clicked, but the "i" that is added to the input field should not be viewable. If the green button is clicked the hidden "i" should be removed.
Here is my HTML live: http://jsfiddle.net/mtYtW/60/
My HTML:
<div class="input string optional">
<label for="company_navn" class="string optional">Name</label>
<input type="text" size="50" name="company[navn]" maxlength="255" id="webhost_navn" class="string optional">
</div>
<div style="width:30px;height:30px;margin-top:10px;display:block;background:green;">
</div>
<div style="width:30px;height:30px;margin-top:10px;display:block;background:red;">
</div>
How to create this functionality?
If you would like to associate data with a specific element, I suggest the .data() method of jQuery. Take a look at the jQuery docs. It's a much cleaner way of accomplishing your goal.
Here's a working Fiddle to get you started.
EDIT
Per the new requirement spelled out in the comments to your question, you can attach to the form submit event like this:
$('#yourForm').submit(function() {
if($('#webhost_navn').data('myData') == 'i')
{
var val = $('#webhost_navn').val();
$('#webhost_navn').val('i' + val);
}
});
NOTE: This code relys on the orginal code in my Fiddle.
It sounds like you want to associate some data with the input field, but not alter the input field's value. For that, you can use the data method:
$(document).ready(function() {
$('#redDiv').click(function() {
$('#webhost_navn').data('myData', 'i');
});
$('#greenDiv').click(function() {
$('#webhost_navn').data('myData', null);
});
});
You'll need to add id's to the red and green divs for the above example to work as is, respectively, redDiv and greenDiv. To retrieve the data you associate with the input, do this:
var myData = $('#webhost_navn').data('myData'); // Will equal 'i' or null
API Ref: http://api.jquery.com/data
EDIT: To append the "i" value to the input's value:
var myData = $('#webhost_navn').data('myData'),
val = $('#webhost_navn').val();
if (myData) {
$('#webhost_navn').val(myData + val);
}
Working example: http://jsfiddle.net/FishBasketGordo/e3yKu/
My update to your code here: http://jsfiddle.net/mtYtW/61/
Basically I gave your red/green button's id's and created a click event to add/remove the content. I also created a css definition for the color of the input box to be white so you don't see the text.
<div class="input string optional"><label for="company_navn" class="string optional"> Name</label><input type="text" size="50" name="company[navn]" maxlength="255" id="webhost_navn" class="string optional"></div>
<div id='green' style="width:30px;height:30px;margin-top:10px;display:block;background:green;"></div>
<div id='red' style="width:30px;height:30px;margin-top:10px;display:block;background:red;"></div>
css:
label {display:block;}
#webhost_navn{color:white};
js:
$("#red").live("click",function()
{
$("#webhost_navn").val("i");
});
$("#green").live("click",function()
{
$("#webhost_navn").val("");
});
Note if the goal is to post an "i" and have nothing else as a value (ie no user input) use <input type='hidden' id=webhost_navn > and use the same jquery code as above without the need for the css.