Display number of Input fields based on the value in database column - javascript

I have a database table with column name qty that holds an int.Now i want to display as many input fields as the value in qty.
So far i haved tried this using iavascript code . Here is my javascript code .
$(function() {
var input = $(<input 'type'="text" />);
var newFields = $('');
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n+1) {
if (n > newFields.length) {
addFields(n);
} else {
removeFields(n);
}
}
});
function addFields(n) {
for (i = newFields.length; i < n; i++) {
var newInput = input.clone();
newFields = newFields.add(newInput);
newInput.appendTo('#newFields');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});

Just store the value in the textfield(hidden)
HTML:
<input type="hidden" id="quantitycount" value="4" />
<div class="textboxarea"></div>
Jquery:
Get the textbox value
var quantitycount=jQuery('#quantitycount').val();
var txthtml='';
for(var txtcount=0;txtcount<quantitycount;txtcount++){
txthtml+='<input type="text" id="txtbox[]" value="" />';
}
jQuery('.textboxarea').html(txthtml);
You can use entry control loops to loop for number of times
Now we can see number of textbox as per need, Just the value from db and store that in the textbox

You can try this
foreach($qty as $qt){
echo '<input type="text">';
}

To append the text fields you need a wrapper on your html form
use some wrapper as mentioned by #Rajesh: and append your text-fields to that wrapper as shown below
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n >0) {
for(var x=0;x<n;x++){
$('#textboxarea').append('<input type="text" name="mytext[]"/>');
}
});
similarly you can write your own logic to remove the text-fields also using jquery

Related

How to get the number of input tags containing certain text?

My goal is to flag when a user enters the same text into one input that matches at least one other input's text. To select all of the relevant inputs, I have this selector:
$('input:text[name="employerId"]')
but how do I select only those whose text = abc, for instance?
Here is my change() event that checks for duplicate text among all the inputs on the page. I guess I am looking for something like :contains but for text within an input.
var inputsToMonitorSelector = "input[type='text'][name='employerId']";
$(inputsToMonitorSelector).change(function() {
//console.log($(this).val());
var inputsToExamineSelector = inputsToMonitorSelector
+ ":contains('" + $(this).val() + "')";
console.log(inputsToExamineSelector);
if($(inputsToExamineSelector).length > 1) {
alert('dupe!');
}
});
Or is there no such selector? Must I somehow select all the inputsToMonitorSelector's and, in a function, examining each one's text, incrementing some local variable until it is greater than one?
With input you need to use [value="abc"] or .filter()
$(document).ready(function() {
var textInputSelector = 'input[type="text"][name="employerId"]';
$(textInputSelector).on('input', function() {
$(textInputSelector).css('background-color', '#fff');
var input = $(this).val();
var inputsWithInputValue = $(textInputSelector).filter(function() {
return this.value && input && this.value == input;
});
var foundDupe = $(inputsWithInputValue).length > 1;
if(foundDupe) {
console.log("Dupe found: " + input);
$(inputsWithInputValue).css('background-color', '#FFD4AA');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="employerId" value="abc">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
[value="abc"] means if the value is abc
[value*="abc"] * means if the value contains abc
[value^="abc"] ^ means if the value starts with abc
[value$="abc"] $ means if the value ends with abc
Note: :contains() not for inputs , and word text not used with inputs and <select>.. inputs and <select> has a value
In your case .. instead of using
$(inputsToExamineSelector).length > 1)
You may need to use .filter()
$(inputsToExamineSelector).filter('[value*="abc"]').length > 1)
OR
$('input[type="text"][name="employerId"]').filter(function(){
return this.value.indexOf('abc') > -1
// for exact value use >> return this.value == 'abc'
}).length;
And to use a variable on it you can use it like
'[value*="'+ valueHere +'"]'
Something like this works. Attach isDuplicated(myInputs,this.value) to a keyup event listener attached to each input.
var myInputs = document.querySelectorAll("input[type='text']");
function isDuplicated(elements,str){
for (var i = 0; i < myInputs.length; i++) {
if(myInputs[i].value === str){
myInputs[i].setCustomValidity('Duplicate'); //set flag on input
} else {
myInputs[i].setCustomValidity(''); //remove flag
}
}
}
Here's another one. I started with vanilla js and was going for an answer like Ron Royston with document.querySelector(x) but ended up with jquery. A first attempt at several things but here you go:
$("input[type='text']").each(function(){
// add a change event to each text-element.
$(this).change(function() {
// on change, get the current value.
var currVal = $(this).val();
// loop all text-element-siblings and compare values.
$(this).siblings("input[type='text']").each(function() {
if( currVal.localeCompare( $(this).val() ) == 0 ) {
console.log("Match!");
}
else {
console.log("No match.");
}
});
});
});
https://jsfiddle.net/xxx8we6s/

validation in if textbox having same values in jquery

I am trying to perform this action like if user choose same value for two different box i have to show some errors.my textbox code as follows.
<input class="order form-control vnumber" type="text" maxlength="1" name="Orderbox[]" required="true">
<input class="order form-control vnumber" type="text" maxlength="1" name="Orderbox[]" required="true">
<input class="order form-control vnumber" type="text" maxlength="1" name="Orderbox[]" required="true">
<input class="order form-control vnumber" type="text" maxlength="1" name="Orderbox[]" required="true">
so the textbox values should be different like 1,2,3,4 it should not be 1,1,1,1 so i have tried real time update using jquery.
$('.order').keyup(function () {
// initialize the sum (total price) to zero
var val = 0;
var next_val=0;
// we use jQuery each() to loop through all the textbox with 'price' class
// and compute the sum for each loop
$('.order').each(function() {
val+=$(this).val();
});
alert(val);
if (next_val==val) {
alert("same value");
}
next_val=val;
});
But its not working as i expected can anybody tell is there any solutions for this.Any help would be appreciated.Thank you.
JFIDDLE:
jfiddle
Try this Demo Fiddle.
var valarr = [];
$('.order').keyup(function () {
var curr = $(this).val();
if (jQuery.inArray(curr, valarr) > -1) {
alert('exists');
} else {
valarr.push(curr);
}
});
You can use arrays to maintain values. To check the existence of value use inArray()
You need to put more of the code inside the .each() loop. Also, change val+= to just val=
$('.order').each(function() {
val=$(this).val();
alert(val);
if (next_val==val) {
alert("same value");
}
next_val=val;
});
And keep in mind next_val is actually the previous value...
fiddle http://jsfiddle.net/phZaL/8/
This will only work if all values entered till now have the same value
jQuery Code
var arr = [];
$('.order').change(function () {
arr.push($(this).val());
if (arr.length > 1) {
if (arr.AllValuesSame()) alert("Values are same");
}
var val = 0;
$.each(arr, function () {
val = parseInt(val) + parseInt(this);
});
$('.val').text(val);
});
Array.prototype.AllValuesSame = function () {
if (this.length > 0) {
for (var i = 1; i < this.length; i++) {
if (this[i] !== this[0]) return false;
}
}
return true;
}
Demo Fiddle
Made with great help from this answer by #Robert

Getting form element by value in Javascript

Hey guys I have a form which is stated below
<td><input type="text" id="NumberofRisks" name="Yeses" style="width: 25px" value ="<?php echo $row['Total-Score'];?> " </td>
The form has some data from a table as a value and I would like to take this value into my Javascript from to do a simple calculation. The function is listed below.
function sum()
{
sumField = document.getElementById("NumberofRisks");
var sum = 0;
$("input[name^='yanswer']:checked").each(function(){
sum++;
});
sumField.value = sum;
}
I need to get that value into the function as the value where it says NumberofRisks. Is there a way I can do this?
Try this to set sum to the initial value of #NumberofRisks.
var prevCheckedCount = 0;
function sum()
{
var sumField = document.getElementById("NumberofRisks");
// start sum with the inital value in HTML from DB
var valueOnClick = Math.floor(sumField.value);
var thisCheckedCount = 0;
$("input[name^='yanswer']:checked").each(function(){
thisCheckedCount++;
});
if(thisCheckedCount <= prevCheckedCount) {
sumField.value = valueOnClick - prevCheckedCount + thisCheckedCount;
} else {
sumField.value =valueOnClick + thisCheckedCount;
}
prevCheckedCount = thisCheckedCount;
}
Here's this code working: http://jsfiddle.net/t5hG4/
In order to grab the value of the input box you can use the following javascript:
var sum = document.getElementById("NumberofRisks").value;
Is this what you're trying to achieve?
As a side note, in the example you provided you did not close the input box so that might be giving you some errors as well.
EDIT:
If you're looking for a pure Javascript way to do this see below:
var elements = document.getElementsByTagName('input');
var sum = document.getElementById("NumberofRisks").value;
for (var i = 0; i < elements.length; i++) {
if (elements[i].checked) {
sum++
}
}
See fiddle - http://jsfiddle.net/es26j/

Add checkbox value to another hidden input field if first hidden field has content

I have a group of 4 checkboxes.
When any two have been checked they have their values copied to two hidden input fields.
The first checked checkbox value goes to the first input id="checkedBox1"
How do I get the second checked checkbox value to go to the second hidden input field id="checkedBox2"
I have used the JavaScript function below to place the values into each input from the individual checkboxes but can't figure out how to iterate through the list of all four checkboxes and place the two checked ones into each separate input field.
Checkboxes:
<input type="checkbox" value="test1" id="a" name="one"><label>Test11</label>
<input type="checkbox" value="test2" id="b" name="one"><label>Test12</label>
<input type="checkbox" value="test3" id="c" name="one"><label>Test13</label>
<input type="checkbox" value="test4" id="d" name="one"><label>Test14</label>
<input type="hidden" value="" id="checkedBox1">
<input type="hidden" value="" id="checkedBox2">
<script>
function populate() {
var checkboxes = document.getElementsByName('one');
var ip1 = document.getElementById('checkedBox1');
var ip2 = document.getElementById('checkedBox2');
// clear current values
ip1.value = ip2.value = '';
var first = false;
var second = false;
// Loop over checkboxes,stop when found 2 that are checked
for (var i=0,iLen=checkboxes.length; i<iLen || !(first && second); i++) {
if (checkboxes[i].checked) {
if (!first) {
ip1.value = checkboxes[i].value;
first = true;
} else if (!second) {
ip2.value = checkboxes[i].value;
second = true;
}
}
}
}
$('input[type="checkbox"]').on('change', function() {
populate();
}).change();
</script>
You could try plain JS, though I would use form property access rather than getElementsByName or getElementById:
function populate() {
var checkboxes = document.getElementsByName('one');
var ip1 = document.getElementById('checkedBox1');
var ip2 = document.getElementById('checkedBox2');
// clear current values
ip1.value = ip2.value = '';
var first = false;
var second = false;
// Loop over checkboxes,stop when found 2 that are checked
for (var i=0,iLen=checkboxes.length; i<iLen || !(first && second); i++) {
if (checkboxes[i].checked) {
if (!first) {
ip1.value = checkboxes[i].value;
first = true;
} else if (!second) {
ip2.value = checkboxes[i].value;
second = true;
}
}
}
}
Edit
Thanks Mal, added a line to clear the values of the hidden inputs each time.

Generic way to detect if html form is edited

I have a tabbed html form. Upon navigating from one tab to the other, the current tab's data is persisted (on the DB) even if there is no change to the data.
I would like to make the persistence call only if the form is edited. The form can contain any kind of control. Dirtying the form need not be by typing some text but choosing a date in a calendar control would also qualify.
One way to achieve this would be to display the form in read-only mode by default and have an 'Edit' button and if the user clicks the edit button then the call to DB is made (once again, irrespective of whether data is modified. This is a better improvement to what is currently existing).
I would like to know how to write a generic javascript function that would check if any of the controls value has been modified ?
In pure javascript, this would not be an easy task, but jQuery makes it very easy to do:
$("#myform :input").change(function() {
$("#myform").data("changed",true);
});
Then before saving, you can check if it was changed:
if ($("#myform").data("changed")) {
// submit the form
}
In the example above, the form has an id equal to "myform".
If you need this in many forms, you can easily turn it into a plugin:
$.fn.extend({
trackChanges: function() {
$(":input",this).change(function() {
$(this.form).data("changed", true);
});
}
,
isChanged: function() {
return this.data("changed");
}
});
Then you can simply say:
$("#myform").trackChanges();
and check if a form has changed:
if ($("#myform").isChanged()) {
// ...
}
I am not sure if I get your question right, but what about addEventListener? If you don't care too much about IE8 support this should be fine. The following code is working for me:
var form = document.getElementById("myForm");
form.addEventListener("input", function () {
console.log("Form has changed!");
});
In case JQuery is out of the question. A quick search on Google found Javascript implementations of MD5 and SHA1 hash algorithms. If you wanted, you could concatenate all form inputs and hash them, then store that value in memory. When the user is done. Concatenate all the values and hash again. Compare the 2 hashes. If they are the same, the user did not change any form fields. If they are different, something has been edited, and you need to call your persistence code.
Another way to achieve this is serialize the form:
$(function() {
var $form = $('form');
var initialState = $form.serialize();
$form.submit(function (e) {
if (initialState === $form.serialize()) {
console.log('Form is unchanged!');
} else {
console.log('Form has changed!');
}
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Field 1: <input type="text" name="field_1" value="My value 1"> <br>
Field 2: <input type="text" name="field_2" value="My value 2"> <br>
Check: <input type="checkbox" name="field_3" value="1"><br>
<input type="submit">
</form>
Form changes can easily be detected in native JavaScript without jQuery:
function initChangeDetection(form) {
Array.from(form).forEach(el => el.dataset.origValue = el.value);
}
function formHasChanges(form) {
return Array.from(form).some(el => 'origValue' in el.dataset && el.dataset.origValue !== el.value);
}
initChangeDetection() can safely be called multiple times throughout your page's lifecycle: See Test on JSBin
For older browsers that don't support newer arrow/array functions:
function initChangeDetection(form) {
for (var i=0; i<form.length; i++) {
var el = form[i];
el.dataset.origValue = el.value;
}
}
function formHasChanges(form) {
for (var i=0; i<form.length; i++) {
var el = form[i];
if ('origValue' in el.dataset && el.dataset.origValue !== el.value) {
return true;
}
}
return false;
}
Here's how I did it (without using jQuery).
In my case, I wanted one particular form element not to be counted, because it was the element that triggered the check and so will always have changed. The exceptional element is named 'reporting_period' and is hard-coded in the function 'hasFormChanged()'.
To test, make an element call the function "changeReportingPeriod()", which you'll probably want to name something else.
IMPORTANT: You must call setInitialValues() when the values have been set to their original values (typically at page load, but not in my case).
NOTE: I do not claim that this is an elegant solution, in fact I don't believe in elegant JavaScript solutions. My personal emphasis in JavaScript is on readability, not structural elegance (as if that were possible in JavaScript). I do not concern myself with file size at all when writing JavaScript because that's what gzip is for, and trying to write more compact JavaScript code invariably leads to intolerable problems with maintenance. I offer no apologies, express no remorse and refuse to debate it. It's JavaScript. Sorry, I had to make this clear in order to convince myself that I should bother posting. Be happy! :)
var initial_values = new Array();
// Gets all form elements from the entire document.
function getAllFormElements() {
// Return variable.
var all_form_elements = Array();
// The form.
var form_activity_report = document.getElementById('form_activity_report');
// Different types of form elements.
var inputs = form_activity_report.getElementsByTagName('input');
var textareas = form_activity_report.getElementsByTagName('textarea');
var selects = form_activity_report.getElementsByTagName('select');
// We do it this way because we want to return an Array, not a NodeList.
var i;
for (i = 0; i < inputs.length; i++) {
all_form_elements.push(inputs[i]);
}
for (i = 0; i < textareas.length; i++) {
all_form_elements.push(textareas[i]);
}
for (i = 0; i < selects.length; i++) {
all_form_elements.push(selects[i]);
}
return all_form_elements;
}
// Sets the initial values of every form element.
function setInitialFormValues() {
var inputs = getAllFormElements();
for (var i = 0; i < inputs.length; i++) {
initial_values.push(inputs[i].value);
}
}
function hasFormChanged() {
var has_changed = false;
var elements = getAllFormElements();
for (var i = 0; i < elements.length; i++) {
if (elements[i].id != 'reporting_period' && elements[i].value != initial_values[i]) {
has_changed = true;
break;
}
}
return has_changed;
}
function changeReportingPeriod() {
alert(hasFormChanged());
}
Here's a polyfill method demo in native JavaScript that uses the FormData() API to detect created, updated, and deleted form entries. You can check if anything was changed using HTMLFormElement#isChanged and get an object containing the differences from a reset form using HTMLFormElement#changes (assuming they're not masked by an input name):
Object.defineProperties(HTMLFormElement.prototype, {
isChanged: {
configurable: true,
get: function isChanged () {
'use strict'
var thisData = new FormData(this)
var that = this.cloneNode(true)
// avoid masking: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
HTMLFormElement.prototype.reset.call(that)
var thatData = new FormData(that)
const theseKeys = Array.from(thisData.keys())
const thoseKeys = Array.from(thatData.keys())
if (theseKeys.length !== thoseKeys.length) {
return true
}
const allKeys = new Set(theseKeys.concat(thoseKeys))
function unequal (value, index) {
return value !== this[index]
}
for (const key of theseKeys) {
const theseValues = thisData.getAll(key)
const thoseValues = thatData.getAll(key)
if (theseValues.length !== thoseValues.length) {
return true
}
if (theseValues.some(unequal, thoseValues)) {
return true
}
}
return false
}
},
changes: {
configurable: true,
get: function changes () {
'use strict'
var thisData = new FormData(this)
var that = this.cloneNode(true)
// avoid masking: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
HTMLFormElement.prototype.reset.call(that)
var thatData = new FormData(that)
const theseKeys = Array.from(thisData.keys())
const thoseKeys = Array.from(thatData.keys())
const created = new FormData()
const deleted = new FormData()
const updated = new FormData()
const allKeys = new Set(theseKeys.concat(thoseKeys))
function unequal (value, index) {
return value !== this[index]
}
for (const key of allKeys) {
const theseValues = thisData.getAll(key)
const thoseValues = thatData.getAll(key)
const createdValues = theseValues.slice(thoseValues.length)
const deletedValues = thoseValues.slice(theseValues.length)
const minLength = Math.min(theseValues.length, thoseValues.length)
const updatedValues = theseValues.slice(0, minLength).filter(unequal, thoseValues)
function append (value) {
this.append(key, value)
}
createdValues.forEach(append, created)
deletedValues.forEach(append, deleted)
updatedValues.forEach(append, updated)
}
return {
created: Array.from(created),
deleted: Array.from(deleted),
updated: Array.from(updated)
}
}
}
})
document.querySelector('[value="Check"]').addEventListener('click', function () {
if (this.form.isChanged) {
console.log(this.form.changes)
} else {
console.log('unchanged')
}
})
<form>
<div>
<label for="name">Text Input:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />
</div>
<div>
<h4>Radio Button Choice</h4>
<label for="radio-choice-1">Choice 1</label>
<input type="radio" name="radio-choice-1" id="radio-choice-1" tabindex="2" value="choice-1" />
<label for="radio-choice-2">Choice 2</label>
<input type="radio" name="radio-choice-2" id="radio-choice-2" tabindex="3" value="choice-2" />
</div>
<div>
<label for="select-choice">Select Dropdown Choice:</label>
<select name="select-choice" id="select-choice">
<option value="Choice 1">Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
</select>
</div>
<div>
<label for="textarea">Textarea:</label>
<textarea cols="40" rows="8" name="textarea" id="textarea"></textarea>
</div>
<div>
<label for="checkbox">Checkbox:</label>
<input type="checkbox" name="checkbox" id="checkbox" />
</div>
<div>
<input type="button" value="Check" />
</div>
</form>
I really like the contribution from Teekin above, and have implemented it.
However, I have expanded it to allow for checkboxes too using code like this:
// Gets all form elements from the entire document.
function getAllFormElements() {
// Return variable.
var all_form_elements = Array();
// The form.
var Form = document.getElementById('frmCompDetls');
// Different types of form elements.
var inputs = Form.getElementsByTagName('input');
var textareas = Form.getElementsByTagName('textarea');
var selects = Form.getElementsByTagName('select');
var checkboxes = Form.getElementsByTagName('CheckBox');
// We do it this way because we want to return an Array, not a NodeList.
var i;
for (i = 0; i < inputs.length; i++) {
all_form_elements.push(inputs[i]);
}
for (i = 0; i < textareas.length; i++) {
all_form_elements.push(textareas[i]);
}
for (i = 0; i < selects.length; i++) {
all_form_elements.push(selects[i]);
}
for (i = 0; i < checkboxes.length; i++) {
all_form_elements.push(checkboxes[i]);
}
return all_form_elements;
}
// Sets the initial values of every form element.
function setInitialFormValues() {
var inputs = getAllFormElements();
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].type != "checkbox"){
initial_values.push(inputs[i].value);
}
else
{
initial_values.push(inputs[i].checked);
}
}
}
function hasFormChanged() {
var has_changed = false;
var elements = getAllFormElements();
var diffstring = ""
for (var i = 0; i < elements.length; i++) {
if (elements[i].type != "checkbox"){
if (elements[i].value != initial_values[i]) {
has_changed = true;
//diffstring = diffstring + elements[i].value+" Was "+initial_values[i]+"\n";
break;
}
}
else
{
if (elements[i].checked != initial_values[i]) {
has_changed = true;
//diffstring = diffstring + elements[i].value+" Was "+initial_values[i]+"\n";
break;
}
}
}
//alert(diffstring);
return has_changed;
}
The diffstring is just a debugging tool

Categories