I have a form with field names that are generated dynamically by server side code.
I am attempting to allow JQuery to manipulate the value of these fields, but am running into trouble.
The generated fields are paired using a unique ID number Example:
A radio button named option_3030
Will have a amount_3030 field
The number of dynamically created fields is also an unknown (there might be one or ten input pairs -- all named option_xxxx and amount_xxxx.
What I'm trying to do is use jquery to set the value of the 3030_amount field when the 3030_option is checked (or unchecked). The problem is, I don't know ahead of time what the actual id number will be.
Any suggestions?
Thanks,
David
One option is to use classes:
<input type="radio" id="3030_Option" class="option" />
<input type="text" id="3030_amount" class="amount" />
<script>
$(function() {
$('.option').click(function() {
$(this).next('.amount').val('new value goes here')
})
})
</script>
By the way starting html ids with numbers is technically not allowed:
ID and NAME tokens must begin with a
letter ([A-Za-z]) and may be followed
by any number of letters, digits
([0-9]), hyphens ("-"), underscores
("_"), colons (":"), and periods (".")
You can grab the id attribute and take the number from it:
$('input[type=radio]').change(function()
{
var id = this.id.split(/_/)[1];
var amount = $('input[name=amount_' + id + ']');
amount.val(123);
}
If you bind your event with a class, and then parse the id of the clicked element to get the numerical identifier to use for the text field.
<input type="radio" id="3030_Option" class="option" />
<input type="text" id="3030_amount" class="amount" />
<input type="radio" id="3031_Option" class="option" />
<input type="text" id="3031_amount" class="amount" />
$('.option').click(function() {
var id = $(this).attr('id');
var num = id.substring(0, id.indexOf('_'));
$('#' + num + '_amount').val('value');
});
As pointed out by others, numerals are not valid as the initial character of an id. It would be better to suffix them. In which case the code needs modifying slightly.
<input type="radio" id="Option_3030" class="option" />
<input type="text" id="amount_3030" class="amount" />
<input type="radio" id="Option_3031" class="option" />
<input type="text" id="amount_3031" class="amount" />
$('.option').click(function() {
var id = $(this).attr('id');
var num = id.substring(id.indexOf('_') + 1, id.length);
$('#amount_' + num).val('value');
});
Mhh i think you could try to register the javascipt function while generating the code. I have done somthing similar with a gridview.
generatedControl.Attributes.Add("onchange", "jqueryFunction(" generatedId ")" );
Related
i have a text box in html, i want to allow user to only input following range
0-9 and NA
there are two cases
1: user inputs range form 0-9 numbers and
2: user inputs only NA (NA denotes Not applicable)
how could i allow user to do this
I try following code but it does not work
<input type = "number" autocomplete="off" class = "form-control" name="Personal_Weapons_Price" id = "Personal_Weapons_Price" required onkeyup="this.value = this.value.toUpperCase();" pattern="[^0-9NA]+" />
Add This Way oninput="this.value = this.value.toUpperCase().replace(/[^NA0-9]/, '')"
<input type="text" oninput="this.value = this.value.toUpperCase().replace(/[^NA0-9]/, '')" />
You could take the following pattern, which looks for one or more digits or NA.
^(\d+|NA)$
The correct pattern is
pattern="^(\d+|NA)$"
If you also want to match na (so you can remove the onkeyup listener):
pattern="^(\d+|NA|na)$"
Edit: if you want to write "NA", you should change the type attribute type from number to text.
<input
type="text"
autocomplete="off"
class="form-control"
name="Personal_Weapons_Price"
id="Personal_Weapons_Price"
required
pattern="^(\d+|NA|na)$"
/>
Sincere apologies if this has been asked and answered elsewhere, I struggled with finding accurate search terms for this.
Working in jQuery I have a var called total. I need to add the value of other vars to total. All the vars in question have numerical values.
This is what I've tried:
var total = total+rocketspend;
$(".totalamount").html(total);
and
var newtotal = total+rocketspend;
var total = newtotal;
$(".totalamount").html(total);
Both have resulted in .totalamount being emptied and replaced with nothing. I have theories around why this might be going wrong - it could be that in the first example a var isn't allowed to be self defining, and it could be that in in the second example the browser attempts to define both newtotal and total at the same time, ending in mystery. Or it could be something else entirely. The rocketspend var works fine on its own, as does total before the attempted addition.
Thoughts?
You only need to use var when you first define a variable. It looks like you're trying to access a variable that already exists. Example:
var total = 0;
var rocketspend = 10;
total = total + rocketspend;
$(".totalamount").html(total);
Additionally, try checking your console for any errors. In most browsers, you can right click and inspect an element or click Ctrl + Shift + I and clicking on the Console tab. You can use Ctrl + Shift + K in Firefox.
You are using jQuery and have referenced an element (i.e. .totalamount) so assuming you are using normal webpage (i.e. HTML, CSS, JS/jQ etc..), this Snippet has 2 <forms>. The first one uses only JavaScript and HTML5. The second form uses jQuery and HTML5.
When using form fields such as <input>, the value you type in them will be a string (i.e. text) value. So when "3" is typed in, the <input> will treat it as text not a real number value. So convert the string to a number, use parseFloat(), parseInt(), or Number().
To get <input> values use .val() (jQuery) or .value (JavaScript).
SNIPPET
$('#calc1').on('input', function() {
var rocket1 = $('#rocket1').val();
var sub1 = $('#sub1').val();
var total1 = parseFloat(sub1) + parseFloat(rocket1);
$("#total1").val(total1);
});
input {width: 8ex;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Using only plain JavaScript and HTML5 form fields</p>
<form id="calc" name="calc" oninput="total.value = parseFloat(sub.value, 10) + parseFloat(rocket.value, 10)">
<fieldset>
<legend>Rocket Expenditure</legend>
<label for="sub">
<b>Sub Total:</b>
<input type="number" id="sub" name="sub" value="0">
</label> +
<label for="rocket">
<b>Rocket:</b>
<input type="number" id="rocket" name="rocket" value="0">
</label>
<label>
<b>Total:</b>
<output name="total" for="sub rocket">0</output>
</label>
</fieldset>
</form>
<p>Using jQuery and HTML5 form fields</p>
<form id="calc1" name="calc1">
<fieldset>
<legend>Rocket Expenditure 1</legend>
<label for="sub1">
<b>Sub Total 1:</b>
<input type="number" id="sub1" name="sub1" value="0">
</label> +
<label for="rocket1">
<b>Rocket 1:</b>
<input type="number" id="rocket1" name="rocket1" value="0">
</label>
<label>
<b>Total 1:</b>
<output id="total1" name="total1" for="sub1 rocket1">0</output>
</label>
</fieldset>
</form>
I'm trying to remove blank spaces from the begining and ending of inputs in general without adding a class or id or event
I tried this live demo but is using onchange event
<javascript>
function trim(el) {
el.value = el.value.
replace(/(^\s*)|(\s*$)/gi, ""). // removes leading and trailing spaces
replace(/[ ]{2,}/gi, " "). // replaces multiple spaces with one space
replace(/\n +/, "\n"); // Removes spaces after newlines
return;
}
</script>
<p>Search1: <input type="text" onchange="return trim(this)" /></p>
<p>Search2: <input type="text" onchange="return trim(this)" /></p>
<p>Search3: <input type="text" onchange="return trim(this)" /></p>
<p>Search4: <input type="text" onchange="return trim(this)" /></p>
<p>Search5: <input type="text" onchange="return trim(this)" /></p>
Somebody can help me about how to make all my inputs trim input values (CSS OR JAVASCRIPT) like this:
<script>
Here in this script will trim blank spaces starting or ending so don't need to add anything in the input
</script>
<input type="text" />
I tried this but is not working
$(.input).text().trim()
Please somebody can help me?.
Thanks in advance.
try $.trim on change input with type text:-
jQuery
$(function(){
$('input[type="text"]').change(function(){
this.value = $.trim(this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Search1: <input type="text"/></p>
<p>Search2: <input type="text"/></p>
<p>Search3: <input type="text"/></p>
<p>Search4: <input type="text"/></p>
<p>Search5: <input type="text"/></p>
Vanilla
window.onload = function() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'text') {
inputs[i].onchange = function() {
this.value = this.value.replace(/^\s+/, '').replace(/\s+$/, '');
};
}
}
}
<p>Search1: <input type="text"/></p>
<p>Search2: <input type="text"/></p>
<p>Search3: <input type="text"/></p>
<p>Search4: <input type="text"/></p>
<p>Search5: <input type="text"/></p>
This is one of the easiest way i found :), it uses jquery hope it helps, it uses your function
The input have to be only:
<input type="text" name="name">
This automatically change all inputs, or you can asign to a class
function trim_text(el) {
el.value = el.value.
replace(/(^\s*)|(\s*$)/gi, ""). // removes leading and trailing spaces
replace(/[ ]{2,}/gi, " "). // replaces multiple spaces with one space
replace(/\n +/, "\n"); // Removes spaces after newlines
return;
}
$(function(){
$("textarea").change(function() {
trim_text(this);
});
$("input").change(function() {
trim_text(this);
});
});
Try this:
function trim(el) {
var trimmedValue = el.val().trim();
el.val(trimmedValue);
}
Your syntax for .trim() is wrong.
To trim a input's value you don't need any regex, just try to change this:
$(.input).text().trim();
to this:
$('input').val().trim();
input is not a class, so you don't have to put the dot before it. Then you have to include it inside ' '. The value of an input is given by val() method, not text().
This will only trim the input's value, you have to use this inside a function in order to make it works properly, as in the example above.
Im trying to create a javascript block inside of a webpage im working on. I havent done javascript since highschool and it doesnt seem to want to come back to me :(
In this block of code i want to have 4 sets of radio buttons, each time a selection is picked,
a price will be inputed to a variable for each radio group. i.e
var firstPrice = $25
var secondPrice = $56
var thirdPrice = $80
var fourthPrice = $90
then after each radio group has one selection there will be a function attached to the submit button that adds up each price to display the final amount inside of a hidden field
var totalPrice = (firstPrice + secondPrice + thirdPrice + fourthPrice)
My question is, how do i attach a number value to a radio button within a group, same name but id is different in each group. Then do i just create a function that adds all the price groups up and then set the submit button to onClick = totalPrice();
Here is an example of one set of radio buttons:
<label>
<input type="radio" name="model" value="radio" id="item_0" />
item 1</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_1" />
item2</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_2" />
item3</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_3" />
Item4</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_4" />
item5</label>
</form>
then my script looks something like:
function finalPrice90{
var selectionFirst = document.modelGroup.value;
var selectionSecond = document.secondGroup.value;
var selectionThird = document.thirdGroup.value;
var selectionFourth = document.fourthGroup.Value;
var totalPrice = (selectionFirst + selectionSecond + selectionThird + selectionFourth);
}
Try this fiddle
http://jsfiddle.net/tariqulazam/ZLQXB/
Set the value attribute of your radio inputs to the price each radio button should represent.
When it's time to calculate, simply loop through each group and get the value attribute if the checked radio.
Because the value attribute is a string representation of a number, you'll want to convert it back to a number before doing any math (but that's a simple parseInt or parseFloat).
Here's a working fiddle using pure JavaScript: http://jsfiddle.net/XxZwm/
A library like jQuery or Prototype (or MooTools, script.aculo.us, etc) may make this easier in the long run, depending on how much DOM manipulation code you don't want to re-invent a wheel for.
Your requirements seem pretty simple, here's an example that should answer most questions. There is a single click listener on the form so whenever there is a click on a form control, the price will be updated.
<script type="text/javascript">
//function updatePrice(el) {
function updatePrice(event) {
var el = event.target || event.srcElement;
var form = el.form;
if (!form) return;
var control, controls = form.elements;
var totalPrice = 0;
var radios;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if ((control.type == 'radio' || control.type == 'checkbox') && control.checked) {
totalPrice += Number(control.value);
}
// Deal with other types of controls if necessary
}
form.totalPrice.value = '$' + totalPrice;
}
</script>
<form>
<fieldset><legend>Model 1</legend>
<input type="radio" name="model1" value="25">$25<br>
<input type="radio" name="model1" value="35">$35<br>
<input type="radio" name="model1" value="45">$45<br>
<input type="radio" name="model1" value="55">$55<br>
</fieldset>
<fieldset><legend>Model 2</legend>
<input type="radio" name="model2" value="1">$1<br>
<input type="radio" name="model2" value="2">$2<br>
<input type="radio" name="model2" value="3">$3<br>
<input type="radio" name="model2" value="4">$4<br>
<fieldset><legend>Include shipping?</legend>
<span>$5</span><input type="checkbox" value="5" name="shipping"><br>
</fieldset>
<input name="totalPrice" readonly><br>
<input type="reset" value="Clear form">
</form>
You could put a single listener on the form for click events and update the price automatically, in that case you can get rid of the update button.
This is a somewhat simplified version of the problem to make it easier to explain and a shorter question.
I have X checkboxes:
<input type="checkbox" class="checker" value="1" />
<input type="checkbox" class="checker" value="2" />
<input type="checkbox" class="checker" value="3" />
...
I have 2 columns, cert and cost, of Y number of input fields (X > Y) then a total at the bottom:
<input type="text" class="cert" /><input type="text" class="cost">
<input type="text" class="cert" /><input type="text" class="cost">
<input type="text" class="cert" /><input type="text" class="cost">
...
<input type="text" id="total" />
The user can select any combination of checkboxes (up to limit Y). When a checkbox is selected, it's value is entered into the first empty cert input. Depending on the cert value, the corresponding cost is then put into the adjacent cost input (e.g. cert 1 = cost 50, cert 2 = cost 100, etc).
If a checkbox is unticked, the corresponding cert is cleared, as is the cost.
The total at the bottom keeps a running total on a change to any thing.
A few additional notes:
The checkboxes are spaced throughout the form, not in one continual sequence.
Similarly the cert and cost inputs are not actually side by side in the html (although do appear to be on the screen), there is other code between them.
Any help / input is greatly appreciated as I'm mostly just producing a mess!
Here is something to start you out with. I'm not sure if your cert 1 cert 2 is going inside the textbox or there are labels or something. Same with your cost. But that's the way I did it in the example. This is assuming you have the same amount of checkboxes as the set of inputs(cert & cost);
$('input.checker').change(function(){
// store the current index so we can pick which text input to change
var $i = $(this).index('input.checker');
// put val in corresponding cert text input
$('input.cert').eq($i).val(this.checked ? 'cert ' + ($i+1) : '');
// put val in corresponding .cost text input
$('input.cost').eq($i).val(this.checked ? 'cost ' + (50 * ($i+1)) : '');
var total = 0;
// loop through the cost inputs and add up total
$('input.cost').each(function(i,v){
total += (+$(v).val().replace('cost ',''));
});
// insert total
$('#total').val(total);
});
EXAMPLE FIDDLE