How to use single input box two value? - javascript

in my Previous i have two separate input box % and $ value looks like this my code :
<tr>
<td>Down payment $</td>
<td>
<input name="downpaymentpc" id="downpaymentpc" type="text" size="8" maxlength="8" onChange="javascript:downPaymentPcChanged(true);" value="<?php echo $min_fha_down_payment;?>" />%</td>
<td colspan="2">Or $
<input name="downpaymentamt" id="downpaymentamt" type="text" size="8" maxlength="8" onChange="javascript:downPaymentAmountChanged(true);" />
</td>
</tr>
this my old code its have two separate input fields its Working well.after that i changed in my new design . i have set single input fields i have to set % and $ image on click change code Looks like
<div class="col-md-2 padding-Zero">
<input name="downpaymentpc" id="downpaymentpc" type="text" class="txt" size="8" maxlength="8" onChange="javascript:downPaymentPcChanged(true);" value="<?php echo $min_fha_down_payment;?>" />
</div>
<div class="col-md-1 padding-lft">
<img src="Content/Images/percent.png" onclick="changeColor(event,this.src)" style="cursor:pointer" />
</div>
i have no idea about it how to set another value in single input fields when i change image % to $ ? any idea about ? please help me ?Really stuck it?
< --NEW -->
In this code don't have id its have only name
<td>Monthly MIP </td>
<td>
<input name="monthlymippc" type="text" size="8" maxlength="8" onChange="javascript:monthlyMIPPcChanged(true)" />
%</td>
<td>Or $
<input name="monthlymipamt" type="text" size="8" maxlength="8" onChange="javascript:monthlyMIPAmountChanged(true)"/>
</td>
My script:
i added extra id in code and i have create this script its not Working..
$(document).ready(function(){
$(".changeImgvalue").click(functon(){
var type=$(this).attr("type");
if(type == 'per'){
$(this).attr({
"type":"amount",
"src":"content/Images/percent.png"
});
$("#monthlymippc").attr("onchange","javascript:monthlyMIPPcChanged(true);");
} else if(type == 'amount'){
$(this).attr({
"type" :"per";
"src":"content/Images/RedDoller.png"
})
$("#monthlymipamt").attr("onchange",onChange="javascript:monthlyMIPAmountChanged(true)")
}
})
})
any error in my code ?

HTML:
<img src="Content/Images/percent.png" type="per" class="changeImg" style="cursor:pointer"/>
Jquery:
$(document).ready(function () {
$(".changeImg").click(function () {
var type = $(this).attr("type");
if (type == 'per') {
$(this).attr({
"type": "amount",
"src": "Content/Images/dollar.png"
});
$("#downpaymentpc").attr("onchange", "downPaymentAmountChanged(true);");
} else if (type == 'amount') {
$(this).attr({
"type": "per",
"src": "Content/Images/percent.png"
});
$("#downpaymentpc").attr("onchange", "downPaymentPcChanged(true);");
}
});
});
HTML:
<img src="Content/Images/percent.png" type="per" class="changeImg" style="cursor:pointer"/>
Jquery:
$(document).ready(function () {
$(".changeImg").click(function () {
var type = $(this).attr("type");
if (type == 'per') {
$(this).attr({
"type": "amount",
"src": "Content/Images/dollar.png"
});
} else if (type == 'amount') {
$(this).attr({
"type": "per",
"src": "Content/Images/percent.png"
});
}
});
});

Related

Input fields value not changing in click function

In my previous code I have used two separate input fields % and $ value. % value code:
<td>
<input name="propertytaxpc" type="text" size="8" maxlength="8" value="<?php echo $dproperty_tax; ?>" onChange="javascript:propertyTaxPcChanged(true)" />
%
</td>
$ value code:
<td>
$
<input name="propertytaxamt" type="text" size="8" maxlength="8" onChange="javascript:propertyTaxAmountChanged(true)" />
</td>
In my new code I have input fields changed the two fields to one field. % and $ values both load single input fields loan. I have set % and $ icon on click. Now input fields default % icon also %. When the user changes icon % to $ the value also needs to change.
<div class="col-md-3 padding-rht">
<input name="propertytaxpc" class="txt" type="text" size="8" maxlength="8" value="<?php echo $dproperty_tax;?>" onChange="javascript:propertyTaxPcChanged(true)" />
</div>
<div class="col-md-1 padding-lft">
<img src="Content/Images/percent.png" onclick="changeColor(event,this.src)" style="cursor:pointer"/>
</div>
function changeColor(event, _src) {
var fname = _src;
var ImageName = fname.substring(fname.lastIndexOf('/') + 1);
//alert(ImageName);
if (ImageName == "percent.png") {
$(event.target).attr("src", "Content/Images/RedDoller.png");
}
else {
$(event.target).attr("src", "Content/Images/percent.png");
}
}
Can any one take look? I have tried many methods, but they're not working? Thanks in advance.
Your question is not very clear, but if I understand correctly I think what you're trying to achieve is for the percent and amount fields to switch visibility according to the $/% image, right?
If so, what you need to do is toggle the two input fields' visibilty, along with changing the image source. Try the code below:
HTML/PHP:
<div class="col-md-3 padding-rht">
<input id="pct" name="propertytaxpc" class="txt" type="text" size="8" maxlength="8" value="<?php echo $dproperty_tax;?>" onChange="javascript:propertyTaxPcChanged(true)" />
<input id="amt" name="propertytaxamt" class="txt" type="text" size="8" maxlength="8" onChange="javascript:propertyTaxAmountChanged(true)" />
</div>
<div class="col-md-1 padding-lft">
<img id="change" src="Content/Images/percent.png" onclick="changeColor(event,this.src)" style="cursor:pointer"/>
</div>
Javascript:
$(document).ready(function() {
$("#amt").hide();
$("#change").click(function() {
changeColor(this);
});
});
function changeColor(elem) {
var $elem = $(elem);
var ImageName = $elem.attr("src");
ImageName = ImageName.substring(ImageName.lastIndexOf('/') + 1);
if (ImageName == "percent.png") {
$elem.attr("src", "Content/Images/RedDoller.png");
} else {
$elem.attr("src", "Content/Images/percent.png");
}
$("#pct, #amt").toggle();
}
An example JS fiddle demonstrating the technique is here: https://jsfiddle.net/ds8txa1j/
This way it works to me. No jquery or extra lib used. There some alert just to check it works...
<div class="col-md-3 padding-rht">
<input name="propertytaxpc" class="txt" type="text" size="8" maxlength="8" value="aaa" onChange="javascript:propertyTaxPcChanged(true)" />
<input name="propertytaxamt" class="txt" type="hidden" size="8" maxlength="8" onChange="javascript:propertyTaxAmountChanged(true)" />
</div>
<div class="col-md-1 padding-lft">
<img src="Content/Images/percent.png" onclick="javascript:changeColor1(this);" style="cursor:pointer"/>
</div>
<script type="text/javascript">
function changeColor1(elem) {
var fname = elem.src;
var ImageName = fname.substring(fname.lastIndexOf('/') + 1);
alert(ImageName);
if (ImageName == "percent.png") {
elem.src = "Content/Images/RedDoller.png";
}
else {
elem.src = "Content/Images/percent.png";
}
alert(elem.src);
}
</script>

jQuery iterate through input fields and disable

I have a question I'm trying to figure out...
I have a lot of inputs in a form, but I only need to iterate through the ones in the div with player class.
<div class="player">
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
</div>
What I need is to iterate through them all once an input field has been modified and calculate how many of the input fields have 0 in them and if its 1 or more than 4 disable submit button.
I've been trying like this but it doesn't seem to work
$(document).ready(function()
{
$(function()
{
var $sum = parseInt($("#sum").text(), 10);
var $num = 0;
if(($sum == 0))
{
$("button[name=submit2]").attr("disabled", "disabled");
}
$(".player input[type=text]").bind("DOMSubtreeModified", function()
{
$.each($("input[type=text]"),function(){
if (!isNaN(+this.value))
{
++$num;
}
});
if (($num > 4) || ($num == 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
});
})
});
I've also tried
$(document).ready(function(){
$(".unit").each(function() {
$(this).keyup(function(){
CheckNull();
});
});
function CheckNull() {
var $num = 0;
$(".unit").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
++$num;
}
});
if (($num > 4) || ($num == 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
}
});
Try changing
if(!isNaN(this.value) && this.value.length!=0) {
++$num;
}
with
if($(this).val() != "" && $(this).val() !=0) {
++$num;
}
to be more jQuery style
I guess this is what you want :
// control function
function checkInputs() {
var num = 0;
// foreach inputs
$(".player input").each(function(i,item) {
var value = $(this).val();
if (value.trim() === "0") {
num++;
}
});
if (num === 1 || num > 4) {
$("#myForm input[type='submit']").attr("disabled", "true");
} else {
$("#myForm input[type='submit']").removeAttr("disabled");
}
}
// if you want a first check after loading the page :
checkInputs();
$(".player input").change(
// This function will be called each time an input change in the player div
checkInputs
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myForm">
<div class="player">
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
</div>
<input type="submit"/>
</form>
I am not sure why are you checking the length? this.value.length!=0
I tweaked your code, here is the fiddle link : http://jsfiddle.net/bLa6evpg/
Hope this help!
I couldn't follow your function, but I believe your problem is that you are running it on page load, and not on the onchange of your input boxes. I achieved the desired functionality by doing that in this codepen
html:
<div class="player">
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number"/>
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
</div>
<button name="submit2">Click</button>
JS:
function validateChanges() {
var playerDiv = document.getElementsByClassName("player")[0];
var inputs = playerDiv.getElementsByTagName("input");
var total = 0;
for(var i = 0; i < inputs.length; i++) {
total += parseInt(inputs[i].value);
}
if(total == 1 || total > 4) { // IF total is 1 or more then 4
document.getElementsByTagName("button")[0].disabled = true;
} else {
document.getElementsByTagName("button")[0].disabled = false;
}
}
looks like i was almost right just messed up a bit Silent_coder fixed this +i added some tricks i saw here
$(document).ready(function(){
CheckNull();
$(".player input").each(function() {
$(this).keyup(function(){
CheckNull();
});
});
function CheckNull() {
var $num = 0;
$(".player input").each(function() {
if(this.value != 0 ) {
$num++;
}
});
if (($num > 4) || ($num <= 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
}
});
Works like i charm for me ^^
Here is a JsFiddle example
$(function () {
$('.unit').on('change', function () {
var units = 0;
$('.unit').each(function (index, value) {
var unit = parseInt($(value).val(),10);
units += unit;
if(units >= 4 || units === 1) {
$('form > button').prop('disabled', true);
} else {
$('form > button').prop('disabled', false);
}
});
});
});

Clearing an input field on blur

I'm attempting to clear all inputs with the class "new" on blur, but for some reason it just won't work. I've bashed my head at the this for three hours now, which obvious point am I missing? Relevant code below.
UPDATE 2
I tried changing out the switch-case block with corresponding if blocks, and they give the expected result. This eliminates the current problem, but I don't find it to be a viable answer to the original question which is why my origianl code with switch-case doesn't work.
UPDATE 1
After some research and experimenting I've discovered that I can clear all inputs with the class "new" as long as they're not inside my switch-case block. The selector I'm testing with is $('.new'), once inside the switch-case block this gives no visible effect.
#{
ViewBag.Title = "Viser infrastruktur";
Layout = "~/Views/Shared/_SuperOfficeLayout.cshtml";
}
<table class="table table-striped compact hover row-border">
<thead>
<tr>
<th>Produsent</th>
<th>Modell</th>
<th>Serienummer</th>
<th>Firmware</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="manufacturer" placeholder="Produsent" value="" />
<input type="hidden" class="autosave new" name="id" value="" />
<input type="hidden" class="autosave new" name="superOfficeCustomerId" value="#Model.SuperOfficeCustomerId" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="model" placeholder="Modell" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="serialNumber" placeholder="Serienummer" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="firmware" placeholder="Firmware" />
</div>
</td>
</tr>
#foreach (var infrastructure in Model.Infrastructures)
{
<tr>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="manufacturer" placeholder="Produsent" value="#infrastructure.Manufacturer" />
<input type="hidden" class="autosave" name="id" value="#infrastructure.Id" />
<input type="hidden" class="autosave" name="superOfficeCustomerId" value="#Model.SuperOfficeCustomerId" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="model" placeholder="Modell" value="#infrastructure.Model" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="serialNumber" placeholder="Serienummer" value="#infrastructure.SerialNumber" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="firmware" placeholder="Firmware" value="#infrastructure.Firmware" />
</div>
</td>
</tr>
}
</tbody>
#section SpecializedScripts
{
<script type="text/javascript">
function saveSettings(element, ajaxUrl, ajaxType) {
var fields = $(element).closest('tr').children('td').children('div').children('.autosave');
var abort = false;
var ajaxData = {};
$(fields).each(function () {
abort = ($(this).val() == '' || $(this).val() == null);
backgroundColor = abort == true ? '#d9534f' : '#f9f598';
$(this).css('background-color', backgroundColor).css('color', '#ffffff').stop().animate({ 'background-color': '#ffffff', 'color': '#000000' }, 1500);
ajaxData[$(this).prop('name')] = $(this).val();
});
if (abort == true) {
return false;
}
$.ajax({
url: ajaxUrl,
type: ajaxType,
data: ajaxData
}).success(function (data, textStatus, jqXHR) {
$(fields).each(function() {
$(this).css('background-color', '#5cb85c').css('color', '#ffffff').stop().animate({ 'background-color': '#ffffff', 'color': '#000000' }, 1500);
});
switch(data.status)
{
case 'Deleted':
$(element).closest('tr').remove();
break;
case 'Added':
var tableBody = $('tbody');
var html = '<tr>';
for (var field in data.result) {
if (field == 'id' || field == 'superOfficeCustomerId')
{
html += '<input type="hidden" class="autosave" name="' + field + '" value="' + data.result[field] + '" />';
}
else {
html += '<td>'
+ '<div class="control-group">'
+ '<input type="text" class="col-md-12 autosave form-control" name="' + field + '" value="' + data.result[field] + '" />'
+ '</div>'
+ '</td>';
$('input.new[name=' + field + ']').val('');
}
}
html += '</tr>';
$(tableBody).append(html);
case 'Modified':
$(fields).each(function () {
$(this).val(data.result[$(this).prop('name')]);
});
break;
}
}).fail(function () {
});
}
$(document).on('blur', 'input.autosave', function () {
saveSettings($(this), '/Link/SaveInfrastructure', 'POST');
});
$(document).on('change', 'input.new', function () {
});
</script>
}
Something like this should work:
$('input.new').on('blur', function() { $(this).val(''); $(this).text(''); });
just make sure the input exists when you bind the event otherwise you can do:
$(document).on('blur', 'input.new', function() { $(this).val(''); $(this).text(''); });
For vanilla JavaScript, you can use
<input onBlur={(event) => { event.target.value = ''; }} />

Auto-complete for random multiple ids

I have random fields for entries. I need to autocomplete using java script and php, but when I try it auto commplete only first field.
My code is:
<script type="text/javascript">
$().ready(function() {
$(".name").keyup(function() {
$(".name").autocomplete("get_profile_list.php", {
width: 260,
matchContains: true,
selectFirst: true
});
});
});
</script>
<script type="text/javascript">
function track() {
var count = jQuery('.abc').length;
jQuery('#track1').append('<span id="track1" class="abc"><br><input type="text" name="name[]" id="name-'+count+'" class="name" value="" size="35"/><input type="text" name="qty[]" id="qty-'+count+'" value="" size="1" onchange="return track();" /><input type="text" name="price[]" id="price-'+count+'" value="" size="1"/></span>');
}
$('input').live("keypress", function(e) {
/* ENTER PRESSED*/
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
var inputs = $(this).parents("form").eq(0).find(":input");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
inputs[0].select()
} else {
inputs[idx + 1].focus(); // handles submit buttons
inputs[idx + 1].select();
}
return false;
}
});
</script>
</head>
<body>
<?php date_default_timezone_set("Asia/Kolkata");?>
<form name="form" method="post">
Party Name : <input type="text" name="customer" size="30" />
Date and Time : <input type="hidden" name="edt" value="<?php echo date("d-m-Y h:i:s", time());?>"/><?php echo date("d-m-Y h:i:s", time());?>
<br><br>
<strong>Products Details</strong>
<div id="main">
<span id="track1" class="abc">
<input type="text" name="name[]" id="name-0" class="name" value="" size="35" /><input type="text" name="qty[]" id="qty-0" value="" size="1" onchange="return track();" /><input type="text" name="price[]" id="price-0" value="" size="1"/>
</span>
<div id="display">
</div>
</div>
<br><br>
Receiver Name<input type="text" name="receiver" /><br>
<input type="submit" name="submit" />
</form>
</body>
</html>
For example please visit http://computerdada.com/slip1.php
In product details first input box is name of product please test it using words
key, lan.
Thanks.
Use .on()
you are adding element with class name dynamically so the elements that are not presernt at DOM ready doesn't get event handler attached to it.
you need Event Delegation to attach the event handler to the parent element present at DOM ready.
$(document).ready(function () {
$('#track1').on('keyup', '.name', function () {
$(this).autocomplete("get_profile_list.php", {
width: 260,
matchContains: true,
selectFirst: true
});
});
});
Updated after OP's comment.
As you are using jQuery v1.3.2
so you have to use .live()
$(document).ready(function () {
$('.name').live('keyup', function () {
$(this).autocomplete("get_profile_list.php", {
width: 260,
matchContains: true,
selectFirst: true
});
});
});

Is insertAdjacentHTML problematic?

I have two functions. The first is the one in which all the input elements will be checked to make sure they are filled correctly. Every thing works well but as the second function comes into action ( The second function 'newInput()' adds inputs ) the first function can not be applied anymore.
The debugger says the emailSec in atpositionSec = emailSec.indexOf("#"), is undefined.
Does any body know the solution??
The markup goes here:
<--!The HTML-->
<form method="post" action="" id="cms" name="cms" onSubmit="return error()">
<table>
<tbody id="myInput">
<tr>
<td>
<label>Role:<span> *</span></label>
<input type="text" name="role" id="role" value="" class="required span3" role="input" aria-required="true" />
</td>
<td>
<label>Email:<span> *</span></label>
<input type="email" name="emailSec" id="emailSec" value="" class="required span3" role="input" aria-required="true" />
</td>
<td>
<button style="height: 20px;" title='Add' onclick='newInput()'></button>
</td>
</tr>
</tbody>
<input type="hidden" name="count" id="count" vale=""/>
</table>
<input type="submit" value="Save Changes" name="submit" id="submitButton" title="Click here!" />
</form>
The First Function:
function error()
{
var emailSec = document.forms['cms']['emailSec'].value,
role = document.forms['cms']['role'].value,
atpositionSec = emailSec.indexOf("#"),
dotpositionSec = emailSec.lastIndexOf(".");
if( topicSec == '' || topicSec == null)
{
alert ("Write your Topic!");
return false;
}
else if(role == '' || role == null)
{
alert ("Enter the Role of the email owner!");
return false;
}
else if(emailSec == '' || emailSec == null || atpositionSec < 1 || dotpositionSec < atpositionSec+2 || dotpositionSec+2 >= emailSec.length)
{
alert ("Enter a valid Email!");
return false;
}
else return true;
}
The Second Function:
//The Javascript - Adding Inputs
var i = 1,
count;
function newInput()
{
document.getElementById("myInput").insertAdjacentHTML( 'beforeEnd', "<tr><td><input type='text' name='role" + i + "' id='role' value='' class='required span3' role='input' aria-required='true' /></td><td><input type='email' name='emailSec" + i + "' id='emailSec' value='' class='required span3' role='input' aria-required='true' /></td><td><button style='height: 20px;' title='Remove' onclick='del(this)'></button></td></tr>");
count = i;
document.forms["cms"]["count"].value = count;
i++;
}
// Removing Inputs
function del(field)
{
--count;
--i;
document.forms["cms"]["count"].value = count;
field.parentNode.parentNode.outerHTML = "";
}
The problem is that after the first addition, document.forms['cms']['emailSec'] becomes an array with all the elements with the name emailSec, so you would need to validate all of them individually using document.forms['cms']['emailSec'][i].
To save you some trouble, you could use the pattern attribute of the input elements in html5 to do this automatically. Furthermore, you could use something like <input type="email" required /> which I think will do almost all the work for you.

Categories