Dynamic textbox creation based on textbox input - javascript

If I give semicolon as input means I have to create a textbox in jQuery. I tried this code and it flows correctly but it didn't show me the result.
$(document).ready(function (){
$("#hellotxt").on('keyup', function (event){
if (event.keyCode == 59)
{
var txt = $("#hellotxt").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
for (var i = 0; i < valueSortArray.length - 1; i++) {
alert("friends");
addbox();
}
}
});
});
addbox code is here
function addbox() {
var table = $(this).closest('table');
if (table.find('input:text').length >= 0) {
table.append('<tr> <input type="text" id="current Name" value="" /></td> <td><input type="text" id="current Name" value="" /> </td></tr>');
}
}
My ASp.Net Markup is
<asp:TextBox ID="hellotxt" runat="server" placeholder="hi;ji;ki;li;"> </asp:TextBox>
<table border="0" cellspacing="2">
<tr>
<td>
<input type="button" id="add" value="Add" />
<input type="button" id="del" value="Del" />
</td>
</tr>

you will get answer from this code..please you all guys check it out
$(document).ready(function (){
//page load
$("#hellotxt").on('keypress', function (event) {
console.log(event.which)
if (event.which == 59 || event.which == 186) {
var txt = $("#hellotxt").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
for (var i = 0; i < valueSortArray.length - 1; i++) {
addbox.call(this, valueSortArray);
}
}
});
function addbox(valueSortArray) {
var table = $(this).next('table').find("tbody");
table.find(".dyn").remove()
$.each(valueSortArray, function (i, v) {
console.log(i,v)
if (v)
table.append('<tr class="dyn"><td><input type="text" value="' + v + '" /></td></tr> ');
})

check below code keycode for ';' is 186 . check working example on fiddle
$("#hellotxt").on('keyup', function (event){
if (event.keyCode == 186)
{
var OBJ = $(this);
var txt = $("#hellotxt").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
for (var i = 0; i < valueSortArray.length - 1; i++) {
addbox(OBJ);
}
}
});
pass $(this)(hellotxt object) as argument in function
function addbox( OBJ ) {
var table = OBJ.next('table');
if (table.find('input').length >= 0) {
table.append('<tr> <input type="text" id="current Name" value="" /></td> <td><input type="text" id="current Name" value="" /> </td></tr>');
}
}

Related

Dynamically change the color or text based on value with Javascript

Hey guys looking for some assistance with changing the color of text based on value. If the value is zero or negative I want it to be red, and if the value is + I want it to be green. Below is just a little bit of code from the full html but I think these are the key parts. Here is a JSFiddle As you can see the table is dynamic. As you input data into the starting amount it will automatically calculate it for the ending amount. The starting amount adds to the bill amount which produces the total amount number. I am also not sure if the event "onchange" is correct. Thank you for your input and advise in advanced.
<p><b>Starting Amount: $ <input id="money" type="number" onkeyup="calc()"></b></p>
<table>
<tr>
<th>Bill Ammount</th>
</tr>
<tr>
<td><input type="number" class="billAmt" id="billAmt" onkeyup="calc()"> </td>
</tr>
</table>
<input type="hidden" id="total" name="total" value="0">
<p><b>Ending Amount: $ <span id="totalAmt" onchange="colorChange(this)">0</span></b></p>
<script type="text/Javascript">
var myElement = document.getElementById('totalAmt');
function colorChange() {
if('myElement' > 0) {
totalAmt.style.color = 'green';
} else {
totalAmt.style.color = 'red';
}
}
function calc() {
var money = parseInt(document.querySelector('#money').value) || 0;
var bills = document.querySelectorAll('table tr input.billAmt') ;
var billTotal = 0;
for (i = 0; i < bills.length; i++) {
billTotal += parseInt(bills[i].value) || 0;
}
totalAmt.innerHTML = money + billTotal;
}
</script>
You can reach the desired result using just one function. Instead of checking the DOM element's innerHTML or textContext to get the amount, just refer to the variables holding it.
var myElement = document.getElementById('totalAmt');
function calc() {
var money = parseInt(document.querySelector('#money').value) || 0;
var bills = document.querySelectorAll('table tr input.billAmt');
var billTotal = 0;
for (i = 0; i < bills.length; i++) {
billTotal += parseInt(bills[i].value) || 0;
}
totalAmt.innerHTML = money + billTotal;
myElement.style.color = money + billTotal <= 0 ? 'red' : 'green';
}
<p><b>Starting Amount: $ <input id="money" type="number" onkeyup="calc()"></b></p>
<table>
<tr>
<th>Bill Ammount</th>
</tr>
<tr>
<td><input type="number" class="billAmt" id="billAmt" onkeyup="calc()"></td>
</tr>
</table>
<input type="hidden" id="total" name="total" value="0">
<p><b>Ending Amount: $ <span id="totalAmt">0</span></b></p>
use myElement.innerHTML instead of myElement in the if condition and invoke the changeColor function at last of calc
var myElement = document.getElementById('totalAmt');
function colorChange() {
if (myElement.innerHTML <= 0) {
totalAmt.style.color = 'red';
} else {
totalAmt.style.color = 'green';
}
}
function calc() {
var money = parseInt(document.querySelector('#money').value) || 0;
var bills = document.querySelectorAll('table tr input.billAmt');
var billTotal = 0;
for (i = 0; i < bills.length; i++) {
billTotal += parseInt(bills[i].value) || 0;
}
totalAmt.innerHTML = money + billTotal;
colorChange();
}
<p><b>Starting Amount: $ <input id="money" type="number" onkeyup="calc()"></b></p>
<table>
<tr>
<th>Bill Ammount</th>
</tr>
<tr>
<td><input type="number" class="billAmt" id="billAmt" onkeyup="calc()"></td>
</tr>
</table>
<input type="hidden" id="total" name="total" value="0">
<p><b>Ending Amount: $ <span id="totalAmt">0</span></b></p>
A couple issues with your original code:
1 - you were checking if the string myElement was greater than zero, instead of the innerHTML of the element you selected.
2 - using innerHTML() to change the contents of an element doesn't fire an onchange event. In my code, I call your colorChange function at the end of the calc function, so if you decide to add another field to it (tax or something), it will be called after the total is calculated.
function colorChange() {
var myElement = document.getElementById('totalAmt');
if (myElement.innerHTML > 0) {
totalAmt.style.color = 'green';
} else {
totalAmt.style.color = 'red';
}
}
function calc() {
var money = parseInt(document.querySelector('#money').value) || 0;
var bills = document.querySelectorAll('table tr input.billAmt');
var billTotal = 0;
for (i = 0; i < bills.length; i++) {
billTotal += parseInt(bills[i].value) || 0;
}
totalAmt.innerHTML = money + billTotal;
colorChange()
}
<p><b>Starting Amount: $ <input id="money" type="number" onkeyup="calc()"></b></p>
<table>
<tr>
<th>Bill Ammount</th>
</tr>
<tr>
<td><input type="number" class="billAmt" id="billAmt" onkeyup="calc()"> </td>
</tr>
</table>
<input type="hidden" id="total" name="total" value="0">
<p><b>Ending Amount: $ <span id="totalAmt">0</span></b></p>

Can I select a multi-dimensional HTML array in JavaScript as a multi-dimensional array?

If I have the following HTML on a page:
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
I would like to select the items using JavaScript (or JQuery) in such a way that I can loop over the items using the outer array.
Currently I have the following JQuery/JavaScript to handle the items:
var items = ($('[name*="item["]'));
var i = 0;
while (i < items.length) {
if (items[i++].value === '') {
// No ID set.
}
else if (items[i++].value === '') {
// No title set.
}
else if (items[i++].value === '') {
// No description set.
}
}
Is there a way to select the elements so that I can loop over them using notation more like the following (Where items.length is 3)?
for (var i = 0; i < items.length; i++) {
if (items[i][0].value === '') {
// No ID set.
}
else if (items[i][1].value === '') {
// No title set.
}
else if (items[i][2].value === '') {
// No description set.
}
}
Or even more like this?
for (var i = 0; i < items.length; i++) {
if (items[i].id.value === '') {
// No ID set.
}
else if (items[i].title.value === '') {
// No title set.
}
else if (items[i].description.value === '') {
// No description set.
}
}
Or would this require more manipulation and processing to go from selecting from the DOM to creating the data structure to loop over?
I think this is exactly what you are looking for (which is not really related to selectors):
function serialize () {
var serialized = {};
$("[name]").each(function () {
var name = $(this).attr('name');
var value = $(this).val();
var nameBits = name.split('[');
var previousRef = serialized;
for(var i = 0, l = nameBits.length; i < l; i++) {
var nameBit = nameBits[i].replace(']', '');
if(!previousRef[nameBit]) {
previousRef[nameBit] = {};
}
if(i != nameBits.length - 1) {
previousRef = previousRef[nameBit];
} else if(i == nameBits.length - 1) {
previousRef[nameBit] = value;
}
}
});
return serialized;
}
console.log(serialize());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
See the related JSFiddle sample.
Here's a way to add a custom function into JQuery to get the data structure you're looking for.
$.fn.getMultiArray = function() {
var $items = [];
var index = 0;
$(this).each(function() {
var $this = $(this);
if ($this.attr('name').indexOf('item[' + index + ']') !== 0)
index++;
if (!$items[index])
$items[index] = {};
var key = $this.attr('name').replace('item[' + index + '][', '').replace(']', '');
$items[index][key] = $this;
});
return $items;
};
var $items = $('input[name^="item["]').getMultiArray();
This allows you to have the references in your "ideal" example.
var $items = $('input[name^="item["]').getMultiArray();
$items[0].id;
JS Fiddle: https://jsfiddle.net/apphffus/

js loop and selecting other input than clicked

I struggle with some task. When I focus on input, the value of other inputs should be cleared. Unfortunately my logic inside the loop fails. Why?
*****EDITED** (Rocket Hazmat tip)
function emptyInputArea(e) {
if(e.target.tagName === 'INPUT') {
currentElem = e.srcElement;
for(var i = 0, total = inputs.length; i < total; i += 1) {
if(currentElem.getAttribute('id') === inputs[i].getAttribute('id')) {
currentIdx = i;
console.log('current index: ' + currentIdx);
}
//while(i !== currentIdx) {
//console.log('show inputs for clear: ' + i);
//inputs[i].value = "";
//}
if(i !== currentIdx) {
console.log('show inputs for clear: ' + i);
inputs[i].value = "";
}
}
}
}
Full code here
I think, this code does what you asked.
function emptyInputArea(e) {
if(e.target.tagName === 'INPUT') {
//Process all inputs.
for(var i = 0; i < inputs.length; ++i) {
//Skip the current input.
if(inputs[i].getAttribute('id') !== e.srcElement.getAttribute('id')) {
//Empty all others.
console.log('show inputs for clear: ' + i);
inputs[i].value = "";
}
}
}
}
How about using a PlaceHolder instead of what you're doing?
<div class="inputs">
<input id="city" type="text" placeholder="some city" />
<input id="postal-code" type="text" placeholder="some code" />
<input id="street" type="text" placeholder="some street" />
<input id="other-details" type="text" placeholder="othe details" />
</div>
Or, if you wanna do that with Javascript, try to use a "data-" attribute:
HTML code:
<div class="inputs">
<input id="city" type="text" data-defaultvalue="some city" />
<input id="postal-code" type="text" data-defaultvalue="some code" />
<input id="street" type="text" data-defaultvalue="some street" />
<input id="other-details" type="text" data-defaultvalue="othe details" />
</div>
jQuery code:
$("input").on("focus", function() {
if ($(this).val() == $(this).data("defaultvalue")) {
$(this).val("");
}
}).on("blur", function() {
if ($(this).val() == "") {
$(this).val($(this).data("defaultvalue"));
}
}).each(function() {
$(this).val($(this).data("defaultvalue"));
});
Pure Javascript code:
var myInputs = document.getElementsByTagName("input");
for (var i = 0; i < myInputs.length; i++) {
var myInput = myInputs[i];
myInput.onfocus = function() {
if (this.value == this.getAttribute("data-defaultvalue")) {
this.value = "";
}
};
myInput.onblur = function() {
if (this.value == "") {
this.value = this.getAttribute("data-defaultvalue");
}
};
myInput.value = myInput.getAttribute("data-defaultvalue");
}

JQuery - Use the value from a function

How can I use the value from a function in an if statement. I have a form where I was using return false in my script but I need changed it to preventDefault.
<form id="percentageBiz" method="post">
<input type="text" id="sum1">
<input type="text" id="sum2">
<input type="submit" onclick="return" value="Get Total">
</form>
<div id="display"></div>​
<script>
$('#percentageBiz').submit(function(e) {
var a = document.forms["percentageBiz"]["sum1"].value;
var b = document.forms["percentageBiz"]["sum2"].value;
var display=document.getElementById("display")
display.innerHTML=parseInt(a,10)+parseInt(b,10);
e.preventDefault();
});
if (display < 100) {
$("#display").addClass("notequal");
}
</script>
$('#percentageBiz').submit(function(e) {
e.preventDefault();
var $display = $("#display", this);
var a = $("#sum1", this).val();
var b = $("#sum2", this).val();
var sum = +a + +b;
$display.text( sum );
if ( sum < 100 ) {
$display.addClass("notequal");
}
});

cant use javascript to run html radio button

I have this script in my < head > :
<script>
var rad = document.getElementsByName('search_type');
alert(rad[1]);
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
(prev)? console.log(prev.value):null;
if(this !== prev) {
prev = this;
}
console.log(this.value)
alert(this.value);
};
}
</script>
and this is my form:
<form name="search_form" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr>
<td class="input">
<input type="radio" name="search_type" value="search_code" checked>1st type<br>
<input type="radio" name="search_type" value="search_title">2nd type<br>
<input type="radio" name="search_type" value="search_filter">3rd type<br>
</td>
<tr/>
</table>
</form>
but none of alerts work. I have no error in console. please help.
You are running the script before the HTML code for the radio buttons has been parsed.
Place the script below the form, or run the code in the load event:
window.onload = function() {
var rad = document.getElementsByName('search_type');
alert(rad[1]);
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
(prev)? console.log(prev.value):null;
if(this !== prev) {
prev = this;
}
console.log(this.value)
alert(this.value);
};
}
};
You could simplify your code with some jQuery:
$(document).ready(function() {
var rad = $('[name="search_type"]');
console.log(rad);
var prev = null;
rad.click(function() {
console.log(prev, $(this).is(':checked'));
if (this !== prev) {
prev = this;
}
console.log(prev, $(this).is(':checked'));
});
});
http://jsfiddle.net/f2aDK/
Move it script after form.
Until Browser parse DOM element, javascript cannot read DOM.
<form name="search_form" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr>
<td class="input">
<input type="radio" name="search_type" value="search_code" checked>1st type<br>
<input type="radio" name="search_type" value="search_title">2nd type<br>
<input type="radio" name="search_type" value="search_filter">3rd type<br>
</td>
<tr/>
</table>
</form>
<script>
var rad = document.getElementsByName('search_type');
alert(rad[1]);
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
(prev)? console.log(prev.value):null;
if(this !== prev) {
prev = this;
}
console.log(this.value)
alert(this.value);
};
}
</script>
first add jquery lib
$(document).ready(function () {
$('[name="search_type"]').live('click', function (event) {
var rad = document.getElementsByName('search_type');
alert(rad[1]);
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
(prev)? console.log(prev.value):null;
if(this !== prev) {
prev = this;
}
console.log(this.value)
alert(this.value);
};
}
});
});

Categories