Javascript innerHtml and value for textbox and label issue - javascript

I have below javascript code.
var txtone = document.getElementByID("txtone");
var lblone = document.getElementByID("lblone");
var tone = txtone.value;
var lone = lblone.innerHTML;
Now the problem is there are cases when I dont have txtone or lblone in my page so in that case last two lines of my code gives error.
solution for this is to check if they exists might be like this code.
var txtone = document.getElementByID("txtone");
var lblone = document.getElementByID("lblone");
if(txtone)
var tone = txtone.value;
if(lblone)
var lone = lblone.innerHTML;
but In my case I have around 100 to 200 textbox and labels with are rendered based on some condition. So in that case I dont think the give solution will be the best one.
Is there any easy way out to my problem something like prototyping value or innerHtml.
(It is an aspx web site page)

Update answer
Check DEMO http://jsfiddle.net/tD6eC/1/
You can use without class or ID like that.
HTML
<label id="">label 1</label><input id="" value="1" /><br />
<label id="">label 2</label><input id="" value="2" /><br />
<label id="">label 3</label><input id="" value="3" /><br />
<label id="">label 4</label><input id="" value="4" /><br />
<label id="">label 5</label><input id="" value="5" /><br />
<div id="content"></div>
JQUERY
$(document).ready(function(){
var val, label;
$('label').each(function(){
val = $(this).html();
label = $(this).next('input').val();
if(val != 'undefined' && label != 'undefined'){
$('#content').append(val+' : '+label+'<br />');
}
});
});

Related

Serializing and deserializing a form with its current state

I have this form
<form id=my_form>
<input id=mt type=text><input id=mc type=checkbox><textarea id=mta />
</form>
I want to have a button somewhere else, that can serialize the form WITH its state, that is, if the textarea has a content, or the text has a content or the checkbox is pressed, I want that information to be stored somehow in the string. Later, I would like to restore the information in the form using that string.
I tried with .innerHTML and it didn't work, I always got the original HTML.
I also looked at the serialize method of jQuery, but I was not able to deserialize it "inside" the form.
Thank you in advance!
Kurt
I've made examples for you. Tested - working fine.
You need jQuery library
First here goes the form:
<form id="my_form">
<input id="formText" type="text" name="formText" />
<br />
<label><input id="formCheck" type="checkbox" name="formCheck" /> check 1</label>
<br />
<label><input id="formCheck2" type="checkbox" name="formCheck2" /> check 2</label>
<br />
<textarea name="formTextarea" id="formTextarea" cols="20" rows="3"></textarea>
<br />
<label><strong>Time unit</strong>:</label>
<p>
<label><input type="radio" name="dataView" value="week" checked="checked" /> Week</label>
<label><input type="radio" name="dataView" value="month" /> Month</label>
<label><input type="radio" name="dataView" value="year" /> Year</label>
</p>
<input type="button" value="Serialize" onclick="serializeForm()" />
<input type="button" value="Unserialize" onclick="restoreForm()" />
</form>
After clicking buttons, corresponding function are called in js
And here is the js:
Serialized data is stored in formData variable, and if needed you can store it in cookie, in database etc... And later load it, regarding your requirements
<script type="text/javascript">
var formData;
function serializeForm() {
formData = $('#my_form').serialize();
}
function restoreForm() {
var obj = unserializeFormData(formData);
// Restore items one by one
if(obj.hasOwnProperty('formTextarea')) {
$('#formTextarea').val(obj.formTextarea);
}
if(obj.hasOwnProperty('formText')) {
$('#formText').val(obj.formText);
}
// Radio buttons
if(obj.hasOwnProperty('dataView'))
$('input[value="'+obj.dataView+'"]').attr('checked', true);
// Restore all checkbox. You can also iterate all text fields and textareas together, because the have same principle for getting and setting values by jQuery
$('#my_form input[type="checkbox"]').each(function(){
var checkName = $(this).attr('name');
var isChecked = false;
if(obj.hasOwnProperty(checkName))
isChecked = true;
$(this).attr('checked',isChecked);
});
}
function unserializeFormData(data) {
var objs = [], temp;
var temps = data.split('&');
for(var i = 0; i < temps.length; i++){
temp = temps[i].split('=');
objs.push(temp[0]);
objs[temp[0]] = temp[1];
}
return objs;
}
</script>

Javascript adding values to radio buttons to input price

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.

jQuery selectors - more elegant solution

Given the following HTML fragment:
<div class="word">
<input type="text" name="A" />
<input type="text" name="n" />
</div>
<div class="word">
<input type="text" name="E" />
<input type="text" name="x" />
<input type="text" name="a" />
<input type="text" name="m" />
<input type="text" name="p" />
<input type="text" name="l" />
<input type="text" name="e" />
</div>
I'd like to write a jQuery script that would concatenate all the ':text' elements' names in a single string, while adding a space when reaching the end of a 'div.word' element.
For example, given the HTML above, the result would be:
An Example
Using my (very) limited jQuery/javascript skills I managed to find a solution, but it involves dirty for ... in loops, so I'd rather not show it here :-).
I'd like to know what is a more elegant/idiomatic (and probably more concise) solution to this problem.
Here's a DEMO: http://jsfiddle.net/ZRukk/1/
var string = $('.word input').map(function() {
var is_last = $(this).is(':last-child');
return this.name + (is_last ? ' ' : '');
}).toArray().join('');
In modern browsers, you could do it without jQuery like this...
Here's a DEMO: http://jsfiddle.net/ZRukk/4/
var inputs = document.querySelectorAll('.word input');
var string = [].map.call(inputs, function(el) {
return el.name + (!el.nextElementSibling ? ' ' : '');
}).join('');
You can do it like this:
var result = [];
$('.word').each(function() {
$(this).find('input').each(function() {
result.push(this.name);
});
result.push(' ');
});
var answer = $.trim(result.join(''));
Working example here: http://jsfiddle.net/jfriend00/DNWSm/
And, a slightly different way of doing it that is probably faster because it's probably less DOM searching:
var result = [];
var lastParent;
$('.word input').each(function() {
// if starting a new parent, add a word separator
if (lastParent && lastParent != this.parentNode) {
result.push(' ');
}
result.push(this.name);
lastParent = this.parentNode;
});
var answer = result.join('');
Working example here: http://jsfiddle.net/jfriend00/bEBGQ/

Why does IE8 fail to resolve my JQuery selector for a checked radio option?

This following line works as expected in Firefox but IE returns 'undefined'.
var selectedChoice = $("input[name='my.test[0].SelectedOption']:checked", '#myForm').val();
Here is a standalone sample that you can run...
Note the problem seems to be the use of '.' and '[]' in the name of the radio element. However this is how ASP.NET MVC renders them. Here is an example which works fine in Firefox but fails in IE.
<html>
<head>
<title>Testing radio selection jquery in IE 8</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script>
</head>
<body>
<form id="myForm">
<input name="selected.Option[0]" id="selected_Option1" type="radio" value="1" checked="checked" />
<label for="selected_Option1">Option 1</label>
<br />
<input name="selected.Option1" id="selected_Option2" type="radio" value="2" checked="checked" />
<label for="selected_Option2">Option 2</label>
<br />
<input name="selectedOption[2]" id="selected_Option3" type="radio" value="3" checked="checked" />
<label for="selected_Option3">Option 3</label>
<br />
<input name="selectedOption3" id="selected_Option4" type="radio" value="4" checked="checked" />
<label for="selected_Option4">Option 4</label>
<br />
<span id="displaySelectedChoice1">No value selected.</span>
<br />
<span id="displaySelectedChoice2">No value selected.</span>
<br />
<span id="displaySelectedChoice3">No value selected.</span>
<br />
<span id="displaySelectedChoice4">No value selected.</span>
</form>
<script language="javascript" type="text/javascript">
var selectedChoice = $("input[name='selected.Option[0]']:checked").val();
$('#displaySelectedChoice1').html('You have selected: ' + selectedChoice);
var selectedChoice = $("input[name='selected.Option1']:checked").val();
$('#displaySelectedChoice2').html('You have selected: ' + selectedChoice);
var selectedChoice = $("input[name='selectedOption[2]']:checked").val();
$('#displaySelectedChoice3').html('You have selected: ' + selectedChoice);
var selectedChoice = $("input[name='selectedOption3']:checked").val();
$('#displaySelectedChoice4').html('You have selected: ' + selectedChoice);
</script>
</body>
</html>
Notice that the 2nd, 3rd and 4th all work but the 1st returns 'undefined' for IE. Its the only one with both '.' and '[]'.
Thanks
Try to escape the square braces in the selector, I don't think IE likes 'em too much. Also, you forgot to close the attribute selector.
var selectedChoice = $('input[name="my.test[0].SelectedOption"]:checked', '#myForm').val();
Or with escaped square braces and periods:
var selectedChoice = $('input[name="my\\.test\\[0\\]\\.SelectedOption"]:checked', '#myForm').val();
Yes, there are 2 backslashes.
I think this will work:
var selectedChoice =
$('input[name="my.test[0].SelectedOption"]:checked', '#myForm').val();
UPDATE:
Replace your JS with this:
var $radio = $('input[name="my\\.test\\[0\\]\\.SelectedOption"]');
$radio.change(function() {
$("#displaySelectedChoice")
.html("You have selected: " + $radio.filter(":checked").val());
});
See working jsFiddle demo
Your select test is invalid javascript:
var selectedChoice = $('input[name='my.test[0].SelectedOption:checked', '#myForm').val();
^--embeded quote breaks the string
This should work better:
var selectedChoice = $("input[name='my.test[0].SelectedOption']:checked", '#myForm').val();
Note that the :checked portion is not in the name= portion
I think you need to escape those [] inside your selector:
var selectedChoice = $("input[name='my.test\\[0\\].SelectedOption']:checked", '#myForm').val();
http://api.jquery.com/category/selectors/
At the top it has an entire paragraph about escaping.
I find your code pretty complicaded. Try something like this:
<form id="myForm">
<input name="my.test[0].SelectedOption" class="test" type="radio" value="1"/>
<label for="my_test_0__SelectedOption_1">Option 1</label>
<br />
<input name="my.test[0].SelectedOption" class="test" type="radio" value="2"/>
<label for="my_test_0__SelectedOption_1">Option 2</label>
<br />
<input name="my.test[0].SelectedOption" class="test" type="radio" value="3"/>
<label for="my_test_0__SelectedOption_1">Option 3</label>
<br />
<span id="displaySelectedChoice">No value selected.</span>
</form>
<script language="javascript" type="text/javascript">
$(".test").change(
function () {
var value = $(this).val();
$("#displaySelectedChoice").replaceTo("you choose: "+value)
}
)
</script>
Dont know wich version of jquery youre using, but even though I red about the new version of jquery that IE has a problem to "see" what you want with this ":checked".
Anyways avoid using this atribute for radio because, well the only checked radio is the one changed anyways.
My point is make a simpler code, it might help.

problem with checkbox statuses

I have a problem, and I can't seem to work out how to solve it. I have two checkboxes, both of them have a value of 5. I just need to add the value of 5 to a variable when a checkbox is checked, and deduct 5, when it is unchecked. I've been using jQuery, but so far I've only managed to add 5 and it adds 10, when both of them are checked. It doesn't deduct anything as of now. Since I have a some radio buttons which I properly check, the code I have is this.
$(":checked").each(function(){
if ($(this).attr("type") == "checkbox"){
pricediff += 5;
}
}
as the function each is used, it adds 10 when both of them are checked. This, of course, is not wanted. And it still has to deduct 5 when the checkbox is unchecked. I have no idea how to do that - I'm a bit of a noob to jQuery and JavaScript. Can anyone assist me? Thanks
P.S. this is not the exact code but just the jist of it.
#rahul has a good answer, but this implies all checkboxes must have a value of 5.
Try this demo: http://jsfiddle.net/2WJZ4/
HTML:
<input type="checkbox" class="test" value="5" />
<input type="checkbox" class="test" value="7" />
<input type="checkbox" class="test" value="2" />
<input type="checkbox" class="test" value="1" /><br />
<span id="result">0</span>
Script:
$(function(){
$("input.test").change(function(){
var $this = $(this);
var value = $this.val();
var checked = $this.is(":checked");
if (checked) value = -value;
var $r = $('#result');
$r.text( (+$r.text()) - value)
});
});
PS. #rahul Awesome fiddle page!!!
Sample HTML
<input type="checkbox" class="test" />
<input type="checkbox" class="test" />
<input type="checkbox" class="test" />
<input type="checkbox" class="test" /><br />
<span id="result">0</span>
Script
$(function(){
$("input:checkbox.test").click(function(){
var checked = $("input:checkbox.test:checked").length;
var checkedValue = checked * 5;
$("#result").text(checkedValue)
});
});
See a working demo
try something like this
var placediff;
function calc()
{
var n = $("input:checked").length;
pricediff = n*5;
}
$(":checkbox").click(calc);

Categories

Resources