Issue with Jquery click not getting called - javascript

I am building an eCommerce Application where the user can select the option and the shopping cart is automatically updated through jquery.
The user will have few radio button to choose from and as he selects the radio button, the shopping cart is updated.
Now, the issue I am facing is, when he taps on the radio button ( Mobile website), some times, the callback function is not called at all so the shopping card is not updated.
I am not an expert, but can you please tell me if I am missing anything. Here is the code I am using.
HTML Code
<div class="col-33">
<div class="panel1 panel-primary text-center no-border">
<div class="panel-body blue">
<label>
<input type="radio" name="recharge_amount" value="{var name='price_id'}"/><br/>{var name='grand_total1'}
<input type="hidden" id="carttotal_{var name='price_id'}" value="{var name='carttotal'}"/>
<input type="hidden" id="taxper_{var name='price_id'}" value="{var name='taxper'}"/>
<input type="hidden" id="taxamount_{var name='price_id'}" value="{var name='taxamount'}"/>
<input type="hidden" id="grand_total_{var name='price_id'}" value="{var name='grand_total'}"/>
</label>
</div>
</div>
</div>
Jquery
$('#transfer_target input[type="radio"]').click(function()
{
$('#cart_total').hide();
var $amt = $(this).val();
var carttotal_el = "#carttotal_" + $amt;
var taxper_el = "#taxper_" + $amt;
var taxamount_el = "#taxamount_" + $amt;
var grand_total_el = "#grand_total_" + $amt;
//update_price_list($amt);
var $carttotal = $('#carttotal');
$carttotal.html($(carttotal_el).val());
var $salestax_per = $('#salestax_per');
var $str = '<h4>Sales Tax(' + $(taxper_el).val() + ')</h4>';
$salestax_per.html($str);
var $salestax_amount = $('#salestax_amount');
$salestax_amount.html($(taxamount_el).val());
var $grand_total = $('#grand_total');
$grand_total.html($(grand_total_el).val());
$('#cart_total').show();
});

Are you using a DOM Ready function? You should have something that looks like this. It may simply be that the data is ready.
$(document).ready(function() {
someName();
});
function someName() {
$('#transfer_target input[type="radio"]').click(function() {
$('#cart_total').hide();
var $amt = $(this).val();
var carttotal_el = "#carttotal_" + $amt;
var taxper_el = "#taxper_" + $amt;
var taxamount_el = "#taxamount_" + $amt;
var grand_total_el = "#grand_total_" + $amt;
var $carttotal = $('#carttotal');
$carttotal.html($(carttotal_el).val());
var $salestax_per = $('#salestax_per');
var $str = '<h4>Sales Tax(' + $(taxper_el).val() + ')</h4>';
$salestax_per.html($str);
var $salestax_amount = $('#salestax_amount');
$salestax_amount.html($(taxamount_el).val());
var $grand_total = $('#grand_total');
$grand_total.html($(grand_total_el).val());
$('#cart_total').show();
});
}

Related

Using Karma Jasmine -how to test do elements and javascript?

Ive been trying for a while to test js and dom elements and finally came across karma which helps to test dom elements. However anything I have so far just doesn't work. Any help would be very much appreciated.
I have been using this tutorial: http://www.bradoncode.com/blog/2015/02/27/karma-tutorial/ but can't get it to work..
js:
window.calculator = window.calculator || {};
(function() {
var result;
var adding = function(one, two) {
var one1 = document.forms["myForm"]["one"].value;
var two2 = document.forms["myForm"]["two"].value;
var one=parseFloat(one.replace(/\,/g,''));
var two=parseFloat(two.replace(/\,/g,''));
result = parseInt(one1) + parseInt(two2);
console.log(result);
var number = document.getElementById("number");
number.innerHTML = result;
console.log(one, two, result)
return result;
}
window.calculator.init = function() {
document.getElementById('add').addEventListener('click', adding);
};
})();
html:
<body>
<form name="myForm">
<h4>numner 1</h4>
<input type="text" name="one" id="one"></input>
<h4>number 2</h4>
<input type="text" name="two" id="two"></input>
<input type="button" id="add">
</form>
<p id="number"> </p>
<script type="text/javascript" src="public/adder.js"></script>
<script>
calculator.init()
</script>
</body>
</html>
test spec:
beforeEach(function() {
var fixture = '<div id="fixture"> <input type="text" name="one" id="one">' +
'<input type="text" name="two" id="two">' +
'<input type="button" id="add" >' +
'<p id="number"> </p></div>';
document.body.insertAdjacentHTML(
'afterbegin',
fixture);
});
// remove the html fixture from the DOM
afterEach(function() {
document.body.removeChild(document.getElementById('fixture'));
});
// call the init function of calculator to register DOM elements
beforeEach(function() {
window.calculator.init();
});
it('should return 3 for 1 + 2', function() {
var x = document.getElementById('one').value = 1;
var y = document.getElementById('two').value = 2;
document.getElementById('add').click();
expect(document.getElementById('number').innerHTML).toBe('3');
});
Here is a working example. Basically all I did was add <form name="myForm"> and </form> to the HTML in the fixture variable and it started working. You want to supply an element to your test that is essentially the same as the element you want to test in the DOM. You can leave out items that aren't important like the <h4> elements that you already did. Otherwise you need to include all the elements that will be required for the tests.
In this case you are looking for values in the form element:
var one1 = document.forms["myForm"]["one"].value;
var two2 = document.forms["myForm"]["two"].value;
var one=parseFloat(one1.replace(/\,/g,''));
var two=parseFloat(two2.replace(/\,/g,''));
But you weren't including the form in your test. You only had the two input elements, the button, and the element where the results are displayed. The following should get you on the right path.
beforeEach(function() {
var fixture = '<div id="fixture">' +
'<form name="myForm">' +
'<input type="text" name="one" id="one">' +
'<input type="text" name="two" id="two">' +
'<input type="button" id="add" >' +
'</form>' +
'<p id="number"> </p></div>';
document.body.insertAdjacentHTML(
'afterbegin',
fixture);
});
// remove the html fixture from the DOM
afterEach(function() {
document.body.removeChild(document.getElementById('fixture'));
});
// call the init function of calculator to register DOM elements
beforeEach(function() {
window.calculator.init();
});
it('should return 3 for 1 + 2', function() {
var x = document.getElementById('one').value = 1;
var y = document.getElementById('two').value = 2;
document.getElementById('add').click();
expect(document.getElementById('number').innerHTML).toBe('3');
});

.replaceWith() not working when replacing a div with another after button click

I am trying to replace a div with another to create a multipage app. I have a div with id = start which holds my form. The form needs to be replaced by the div with id = list when the button is clicked. The form is getting reloaded and I am not getting any error in the console either.
HTML:
<div data-role="page" id="start">
<div data-role = "main">
<br><br>
<div align="right">
<img src="./img/help-icon.png" onClick="alert('Please get your security credentials')"/>
</div>
<div align = "center">
<img src="./img/Logo login screen.png" height="200" width="170"/>
</div>
<br><br>
<form id="loginForm" align = "center" method="get">
<div id="user" align = "center">
<input type="text" id="accessKey" Placeholder="Access Key (20 characters)" size="30" maxlength="128" tabindex="1" autocorrect="off" autocapitalize="off" data-validation="[NOTEMPTY]"/>
</div>
<br><br>
<div id = "pass" align = "center">
<input type="password" id = "secretKey" Placeholder = "Secret Key (40 characters)" size="30" maxlength="1024" tabindex="2" data-validation="[NOTEMPTY]"/>
</div>
<br><br>
<center><button type = "submit" id="submitButton" class="ui-btn">Login</button></center>
</form>
</div>
</div>
<div data-role="page" id="list">
<div data-role="main">
<div id="bucket_list"></div>
<div id = "status"></div>
</div>
</div>
JS snippet:
AWS.config.update({accessKeyId: accKey, secretAccessKey: secKey});
var s3Client = new AWS.S3();
s3Client.listBuckets(function(err, data){
$('#start').replaceWith($('#list'));
if(err) alert("Error :: ", err);
else{
var listElement = document.createElement("ul");
document.getElementById('bucket_list').appendChild(listElement);
for(var index in data.Buckets){
var bucket = data.Buckets[index];
var listContent = document.createElement("li");
listContent.innerHTML = "<p><a href=# onclick =" + bucketContents(bucket) + "; >" + bucket.Name + "</a></p>";
listElement.appendChild(listContent);
}
}
});
function bucketContents(bucket){
s3Client.listObjects(params = {Bucket: bucket.Name}, function(err, data){
if (err) {
document.getElementById('status').innerHTML = 'Could not load objects from S3';
} else {
document.getElementById('status').innerHTML = 'Loaded ' + data.Contents.length + ' items from S3';
var listStart = document.createElement("ul");
document.getElementById('status').appendChild(listStart);
for(var i=0; i<data.Contents.length;i++){
var listItems = document.createElement("li");
listItems.innerHTML = data.Contents[i].Key;
listStart.appendChild(listItems);
}
}
});
}
Can anyone tell me where I am going wrong?
Make sure you are adding jquery library properly. Mind that your code should be written AFTER you add the jquery library.
ALITER
What i get from your code is you want to make #start invisible and then make #list visible.
you can add display : none to CSS of #list and then at the event when you want to do that operation, you can do the following :
$('#start').hide();
$('#list').show();
Thanks for all the help. I got my answer. I just need to place the replaceWith in the proper place. The working code is:
AWS.config.update({accessKeyId: accKey, secretAccessKey: secKey});
var s3Client = new AWS.S3();
s3Client.listBuckets(function(err, data){
if(err) alert("Error :: ", err);
else{
var listElement = document.createElement("ul");
document.getElementById('bucket_list').appendChild(listElement);
for(var index in data.Buckets){
var bucket = data.Buckets[index];
var listContent = document.createElement("li");
//listContent.innerHTML = "<p><a href=# onclick =" + bucketContents(bucket) + "; >" + bucket.Name + "</a></p>";
listContent.innerHTML = "<p><a href='#'>" + bucket.Name + "</a></p>";
listElement.appendChild(listContent);
}
}
});
$("#start").replaceWith($("#list").html());

Trigger a html button inside a web browser control

in my web browser control i am accessing a form:
<form role="form">
<div class="form-group">
<input type="text" class="form-control" id="InputEmail1" placeholder="name...">
</div>
<div class="form-group">
<input type="email" class="form-control" id="InputPassword1" placeholder="email...">
</div>
<div class="form-group">
<textarea class="form-control" rows="8" placeholder="message..."></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
How can i trigger this button automatically from vb.net application? how can i set text to the text area? am accessing the text box as follows:
WebBrowser1.Document.GetElementById("InputEmail1").SetAttribute("value", "Sample")
WebBrowser1.Document.GetElementById("InputPassword1").SetAttribute("value", "Sample")
i cannot access button and text area since it does not have an id or name? is their any possibility to do like this?
Your elements need to have IDs and if you doesn't have access to the html code you can enumerate elements like this but you must know which element is the right one:
foreach (HtmlElement element in WebBrowser1.Document.Forms[0].All)
{
if (element.TagName.ToLower() == "textarea".ToLower())
{
element.InnerText = "text";
}
}
for clicking a button try this:
element.InvokeMember("click");
In a lot of web automation, unless you can get the original devs to add ids, you have to navigate the DOM in order to find what you need.
Here is an example of doing that kind of filtering and web automation
var actionPanel = topPanel.insert_Above(40);
var ie = topPanel.add_IE_with_NavigationBar().silent(true);
var server = "http://127.0.0.1.:8080";
Action<string,string> login =
(username, password) => {
ie.open(server + "/jpetstore/shop/signonForm.do");
ie.field("username",username);
ie.field("password",password);
ie.buttons()[1].click();
};
Action loginPlaceAnOrderAndGoToCheckout =
()=>{
ie.open("http://127.0.0.1:8080/jpetstore");
ie.link("Enter the Store").click();
//login if needed
var signOffLink = ie.links().where((link)=> link.url().contains("signonForm.do")).first();
if(signOffLink.notNull())
{
signOffLink.click();
login("j2ee", "pwd1");
}
ie.links().where((link)=> link.url().contains("FISH"))[0].click();
ie.link("FI-FW-01 ").flash().click();
ie.links().where((link)=> link.url().contains("addItemToCart"))[0].flash().click();
ie.links().where((link)=> link.url().contains("checkout.do"))[0].flash().click();
ie.links().where((link)=> link.url().contains("newOrder.do"))[0].flash().click();
};
Action scrollToTotal =
()=>{
var tdElement = ie.elements().elements("TD").toList().Where((element)=> element.innerHtml().notNull() && element.innerHtml().contains("Total:")).first();
tdElement.scrollIntoView();
tdElement.injectHtml_beforeEnd("<h2><p align=right>Look at the Total value from the table above (it should be 18.50)</p><h2>");
};
Action<string> exploit_Variation_1 =
(payload) => {
loginPlaceAnOrderAndGoToCheckout();
ie.buttons()[1].flash().click();
ie.open(server + "/jpetstore/shop/newOrder.do?_finish=true&" + payload);
scrollToTotal();
};
Action<string> exploit_Variation_1_SetTotalPrice =
(totalPrice) => {
var payload = "&order.totalPrice={0}".format(totalPrice);
exploit_Variation_1(payload);
};
Another option (which I also use quite a lot) is to actually use Javascript to do those actions (which is much easier if jQuery is available (or injected) in the target page).
[Test] public void Issue_681__Navigating_libraries_views_folders__Clicking_the_icon_doesnt_work()
{
var tmWebServices = new TM_WebServices();
Func<string, string> clickOnNodeUsingJQuerySelector =
(jQuerySelector)=>
{
ie.invokeEval("TM.Gui.selectedGuidanceTitle=undefined");
ie.invokeEval("$('#{0}').click()".format(jQuerySelector));
ie.waitForJsVariable("TM.Gui.selectedGuidanceTitle");
return ie.getJsObject<string>("TM.Gui.selectedGuidanceTitle");
};
if (tmProxy.libraries().notEmpty())
{
"Ensuring the the only library that is there is the TM Documentation".info();
foreach(var library in tmProxy.libraries())
if(library.Caption != "TM Documentation")
{
"deleting library: {0}".debug(library.Caption);
tmProxy.library_Delete(library.Caption);
}
}
UserRole.Admin.assert();
tmProxy.library_Install_Lib_Docs();
tmProxy.cache_Reload__Data();
tmProxy.show_ContentToAnonymousUsers(true);
ieTeamMentor.page_Home();
//tmWebServices.script_Me_WaitForClose();;
//ieTeamMentor.script_IE_WaitForComplete();
ie.waitForJsVariable("TM.Gui.selectedGuidanceTitle");
var _jsTree = tmWebServices.JsTreeWithFolders();
var viewNodes = _jsTree.data[0].children; // hard coding to the first library
var view1_Id = viewNodes[0].attr.id;
var view5_Id = viewNodes[4].attr.id;
var click_View_1_Using_A = clickOnNodeUsingJQuerySelector(view1_Id + " a" );
var click_View_5_Using_A = clickOnNodeUsingJQuerySelector(view5_Id + " a" );
var click_View_1_Using_Icon = clickOnNodeUsingJQuerySelector(view1_Id + " ins" );
var click_View_5_Using_Icon = clickOnNodeUsingJQuerySelector(view5_Id + " ins" );
(click_View_1_Using_A != click_View_5_Using_A ).assert_True();
(click_View_5_Using_A == click_View_1_Using_Icon).assert_False(); // (Issue 681) this was true since the view was not updating
(click_View_5_Using_A == click_View_5_Using_Icon).assert_True();
}

Display image on radio select and add price

im trying to select club and display image and return price using radio buttons.
Im stuck because I cannot get the pictures to display. any ideas what could i add?
<label>Select Club:</label><br>
<UL>
<label class="radiolabel"><input type="radio" name="SelectedJersy" value="MUFC" onclick="displayJersy()"> MUFC-(15€)</label><br>
<label class="radiolabel"><input type="radio" name="SelectedJersy" value="MCFC" onclick="displayJersy()"> MCFC-(20€)</label><br>
</UL>
<div id='jersy'></div>
<script type="text/javascript">
var img_Jersy = new Array();
img_Jersy["MUFC"]= "<img src='data/images/MUFC.png'>";
img_Jersy["MCFC"]= "<img src='data/images/MCFC.png'>";
var jersy_prices = new Array();
jersy_prices["MUFC"]=15;
jersy_prices["MCFC"]=10;
function displayJersy()
{
var jersyPrice=0;
var theForm = document.forms["tshirtform"];
var selectJersy = theForm.elements["SelectedJersy"];
for(var i = 0; i < selectJersy.length; i++)
{
//if the radio button is checked
if(selectJersy[i].checked)
{
jersyPrice = jersy_prices[selectJersy[i].value];
//imgJersy = img_Jersy[selectJesry[i].value];
imgJersy = img_Jersy[selectJesry[i].value];
document.getElementById("jersy").innerHTML =imgJersy;
document.getElementById('jersy').style.visibility="visible";
break;
}
return jersyPrice;
}
</script>
I see a couple issues. You forgot a closing curly brace in your for loop.
There's a typo here:
imgJersy = img_Jersy[**selectJesry**[i].value];
Anyway, here's a working version: http://jsfiddle.net/z92togqd/2/

dynamically add variables in array

i have a script that add educational record to my database. my point is that i want to add variable dynamically depending upon the values user add. following is the script and jsfiddle example to show.
$(function() {
var inc =1;
$('.add').live('click',function(){
var $val1= $('.val1').val();
var $val2= $('.val2').val();
var $val3= $('.val3').val();
var $val4= $('.val4').val();
var result = $val1 + $val2 +$val3 +$val4;
var hiddin="get_val"+inc;
var edu="edu"+inc;
var grade="grade"+inc;
var grp="grp"+inc;
var colg="colg"+inc;
//alert(hiddin);
$('<div class='+hiddin+' style="display:block;">'+'<span class='+edu+'>'+$val1+'</span>'+'<span class='+grade+'>'+$val2+'</span>'+'<span class='+grp+'>'+ $val3 +'</span>' +'<span class='+colg+'>' +$val4 +'</span>'+ '</div>').appendTo('.wrap');
// alert(result);
var $val1= $('.val1').val('');
var $val2= $('.val2').val('');
var $val3= $('.val3').val('');
var $val4= $('.val4').val('');
inc++;
});
$('.submit').live('click',function(){
var $edu1= $('.edu1').html();
var $edu2= $('.edu2').html();
var $edu3= $('.edu3').html();
var $edu4= $('.edu4').html();
var $grade1= $('.grade1').html();
var $grade2= $('.grade2').html();
var $grade3= $('.grade3').html();
var $grade4= $('.grade4').html();
var $grp1= $('.grp1').html();
var $grp2= $('.grp2').html();
var $grp3= $('.grp3').html();
var $grp4= $('.grp4').html();
var $colg1= $('.colg1').html();
var $colg2= $('.colg2').html();
var $colg3= $('.colg3').html();
var $colg4= $('.colg4').html();
alert($edu4 + $colg3 + $grp2 + $grade3);
});
});
following is the link http://jsfiddle.net/Apexusman/g7PSH/5/
please help
I suggest you to set some hidden variables to span and get the value. something like this
$('<div class='+hiddin+' style="display:block;">'+'<span class='+edu+'><input type="hidden" name="edu[]" id="edu_'+inc+'" value="'+$val1+'" >'+$val1+'</span>'+'<span class='+grade+'><input type="hidden" name="grade[]" id="grade_'+inc+'" value="'+$val2+'" >'+$val2+'</span>'+'<span class='+grp+'><input type="hidden" name="group[]" id="group_'+inc+'" value="'+$val3+'" >'+ $val3 +'</span>' +'<span class='+colg+'><input type="hidden" name="college[]" id="college_'+inc+'" value="'+$val4+'" >' +$val4 +'</span>'+ '</div>').appendTo('.wrap');
and change the html
<form id="save_form">
<div class="wrap"> </div>
</form>
and get the values by using jquery serialize
var data_save = $("#save_form").serialize();
alert(data_save);

Categories

Resources