Get dynamic elements from page HTML? - javascript

I am new to the front end development but have quite a bit of back end dev experience. I've tried a few different approaches to the javascript below and that is just some of the things I tried.
I have the following code that shows the products. This is in n for each loop from my product list.
At the bottom of the page i have the add button.
I need to get the data-Id of each product to get the productId, price to get the price and the value of the qty input field so that I can send it through to my cart.
I can't get those values and have tried a few different things.
<div class="col-md-2">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">#Html.DisplayFor(modelItem => product.Code)</h3>
</div>
<div class="panel-body">
<div class="text-center" id="user_image">
<img src="../../images/chickenBreast.jpg" class="img-thumbnail" />
</div>
<br />
<div class="panel-body form-group-separated">
<div class="form-group">
<label class="control-label">Short Description:</label>
<p>#Html.DisplayFor(modelItem => product.Description)</p>
</div>
<div class="form-group">
<label class="control-label">Long Description:</label>
<p>#Html.DisplayFor(modelItem => product.LongDescription)</p>
</div>
</div>
<div class="panel-footer">
<form class="form-inline" role="form">
<div class="form-group">
<input id="qty" data-id="#product.Id" price="#product.Price" type="text" class="Product-control" placeholder="Qty" />
</div>
<button id="AddButton" class="btn btn-primary pull-right">Add to cart</button>
</form>
</div>
</div>
</div>
</div>
Here is my javascript, I have tried a few different things but nothing seems to give me the required data
<script type="text/javascript" src="../../Scripts/js/plugins/jquery/jquery.min.js"></script>
<script type="text/javascript">
$("#AddButton").click(function (form) {
var productToUpdate = $("input").parent().find("data-id");
var countToUpdate = $('input[id="qty"]', form).val();
var productPrice = $(this).parent().find('price').val();
if (productToUpdate != '') {
// Perform the ajax post
$.post("~/Cart/GetCartItems", { "productId": productToUpdate, "qty": countToUpdate, "price": productPrice },
function (data) {
//Check for not process the callback data when server error occurs
//if (data.ItemCount != -1) {
// $('#cart-total').text(data.CartTotal);
//}
});
}
});
</script>

The selector data-id will never match. That is suggesting that data-id is an element type as (example) <data-id ...></data-id> try using find('input[data-id]') instead.
https://api.jquery.com/category/selectors/attribute-selectors/
https://api.jquery.com/has-attribute-selector/
Description: Selects elements that have the specified attribute, with
any value.
Example from documentation:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>attributeHas demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>no id</div>
<div id="hey">with id</div>
<div id="there">has an id</div>
<div>nope</div>
<script>
// Using .one() so the handler is executed at most once
// per element per event type
$( "div[id]" ).one( "click", function() {
var idString = $( this ).text() + " = " + $( this ).attr( "id" );
$( this ).text( idString );
});
</script>
</body>
</html>
// Using .one() so the handler is executed at most once
// per element per event type
$("div[id]").one("click", function() {
var idString = $(this).text() + " = " + $(this).attr("id");
$(this).text(idString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>attributeHas demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>no id</div>
<div id="hey">with id</div>
<div id="there">has an id</div>
<div>nope</div>
<script>
</script>
</body>
</html>

I figured out the hierarchies
here is my solution
HTML
<div class="panel-footer">
<form class="form-inline" role="form">
<div class="form-group">
<input id="qty" type="text" class="Product-control" placeholder="Qty" />
</div>
<button id="AddButton" data-id="#product.Id" price="#product.Price" class="btn btn-primary pull-right">Add to cart</button>
</form>
</div>
The javascript
<script type="text/javascript" src="../../Scripts/js/plugins/jquery/jquery.min.js"></script>
<script type="text/javascript">
$("#AddButton").click(function () {
var productId = $(this).attr('data-id');
var productPrice = $(this).attr('price');
var qty = $(this).prev().children(".Product-control").val();
if (productId != '') {
// Perform the ajax post
$.post("~/Cart/GetCartItems", { "productId": productId, "qty": qty, "price": productPrice },
function (data) {
//Check for not process the callback data when server error occurs
//if (data.ItemCount != -1) {
// $('#cart-total').text(data.CartTotal);
//}
});
}
});
</script>

Related

How to return a sum of a list of json object values in HTML

I am building a html form which based on that, when user submits his/her name it should return an integer representing sum of all bought items by user, the return value from API is a list of json formate, which looks like this:
[{"Phone":800}, {"laptop":1500}, {"car":12000},{"watch":300}]
This is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="MyMain.css">
<script language="JavaScript">
function myFunction() {
document.getElementById('myshow').innerHTML =
document.getElementById("Name").value;
return false;
}
</script>
</head>
<body>
<div class="container">
<div>
<fieldset>
<form method="POST" action="" onSubmit="return myFunction();">
<div class="row">
<div form-group">
<label for="fname">Your Name: </label>
<input type="text" class="form-control" name="name" id="Name" placeholder="Jon" value="">
</div>
</div>
<div>
<input type="submit" class="button" value="Submit"><br/>
</div>
</div>
</form>
</fieldset>
</div>
</div>
<div class="container">
<fieldset>
<div>
<label>Prices: </label>
<p><span id='myshow'></span></p>
</div>
</fieldset>
</div>
</body>
</html>
I have no idea how to get that response and how to sum values of items!
Short answer of your question is :
var a = '[{"Phone":800}, {"laptop":1500}, {"car":12000},{"watch":300}]';
// parse your json to object if your json is string and not generated by js
a = JSON.parse(a);
var sum = 0;
Object.values(a).forEach(function(ww){
sum += Object.values(ww)[0]; // get sum of every object item value.
});
console.log(sum);
Use reduce() method in JavaScript.
let data = [{"Phone":1}, {"laptop":1}, {"car":1},{"watch":1}]
let total = data.reduce((acc, value) => {
return acc + value[Object.keys(value)[0]]
}, 0)
console.log(total);

Total of input fields should not exceed certain Amount

I have created an Add / Remove input fields. I want to get total of 'Amount' using Javascript which should not exceed 100%. Means the total of amount should not exceed 10000.
Say for example first field will have 3000, second will have 6000 and third will have 1000. If we enter larger number it should not accept it.
var i = 0;
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
return false;
});
});
var rows = '<div class="fund-fields"><div class="row"><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]" placeholder=""></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="allocate_amount[]" placeholder=""></div></div><div class="col-md-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</button></div></div><div class="clear"></div></div>';
//add input
$('#add-allocation-fields').click(function() {
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel panel-default">
<div class="panel-heading">
<center><b>Allocation of Funds</b></center>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-5">
<label>Allocation Items <b style="color:#FF0000;">*</b></label>
</div>
<div class="col-md-5">
<label>Amount <b style="color:#FF0000;">*</b></label>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_items[]" placeholder="">
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_amount[]" placeholder="">
</div>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add
</button>
</div>
</div>
<div id="fund-allocation-fields"></div>
<p class="help-block"><i>Total amount must be equal to the goal amount.</i></p>
</div>
</div>
Please Help me. Thanks in advance.
If I understand correctly you could do something as simple as:
var val1 = document.getElementById('inputOne').value;
var val2 = document.getElementById('inputTwo').value;
var val3 = document.getElementById('inputThree').value;
if(val1+val2+val3 < 10000){
// Less then 10000 so do your stuff
} else{
// More then 10000 so let the user know they went too far
}
You can also do it in jQuery. Just change document.getElementById('inputOne').value to $('#inputOne').val()
If the elements are built dynamically you could just do something like this:
var inputs = Array.from(document.querySelectorAll('.inputsToAdd'));
var number = 100;
document.getElementById('btn').addEventListener('click', ()=>{
inputs.map(input=>{
number+=parseInt(input.value);
})
if(number<10000)
console.log(true);
else console.log(false)
})
This is a bit of a connundrum since you have the ability to add infinite input fields, in common practice this is a bad UI experience but to resolve your issue.
You want to sum all the values on click and if the values are too high throw an error. You can accomplish this by assigning each inputField a class and then summing the collection of that class.
I made a small sample using jQuery, a conditional and .each() like so:
$('#sum').click(function(){
var nums = 0
$('.valueField').each(function(){
nums += parseInt(this.value)
});
nums > 10000 ? console.log("value too high", nums) : console.log("compute works", nums)
})
See my small demo below:
$('#sum').click(function() {
var nums = 0
$('.valueField').each(function() {
nums += parseInt(this.value)
});
nums > 10000 ? alert("value too high", nums) : alert("compute works", nums)
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type='number' class='valueField' />
<input type='number' class='valueField' />
<input type='number' class='valueField' />
<button id='sum'>Click</button>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>

Can't get right value for element id in jquery

I need to get the value of the id attribute of an element.
javascript:
function checkPhoneZip() {
$.get(encodeURI("checkPhoneZip.aspx?mobilePhone=" + $("#mobilePhone").val() + "&postalCode=" + $("#postalCode").val()), function (data) {
$("#ajaxResults").html(data);
})
.done(function () {
var divs = $("#ajaxResults").find('div');
if (divs.length == 1) {
if ($("#ajaxResults").html() == "<div>dbEmpty<div>") {
$("#emailGetError").text("Cannot find an email address for the information entered");
}
else {
$("#user").val($("#ajaxResults").text())
$("#user").focus();
$("#emailRecovery").slideUp();
}
}
else {
var options = "";
for (i = 0; 1 < divs.length; i++) {
options += "<option value='" + $(divs[i]).attr("id") + "'>" + $(divs[i]).text() + "</option>";
}
$("#companies").html("<option selected>Select which business you are</option>" + options);
$("#companies").slideDown('fast');
}
})
.fail(function () { alert("Failed to contact Database. Please try again in a few seconds"); })
;
}
html
<%# Page Language="C#" AutoEventWireup="true" CodeFile="passwordReset.aspx.cs" Inherits="passwordReset" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="https://jquery-ui.googlecode.com/svn/tags/latest/ui/jquery.effects.core.js"></script>
<script type="text/javascript" src="https://jquery-ui.googlecode.com/svn/tags/latest/ui/jquery.effects.slide.js"></script>
<link href='https://fonts.googleapis.com/css?family=Paytone+One' rel='stylesheet' type='text/css'/>
<link href='https://fonts.googleapis.com/css?family=Dosis:800' rel='stylesheet' type='text/css'/>
<style type="text/css">
.link{text-decoration:underline;cursor:pointer}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="getCode" runat="server">
<div>Enter the email address associated with your account and a verification code will be texted to the mobile phone number you used to sign up.</div>
<div>
<input id="user" runat="server" type="email" />
<div id="userError"></div>
</div>
<div>
<button type="button" id="getCodeButton">GET CODE</button>
</div>
<div class="link" id="forgotEmail">Forgot email address?</div>
</div>
<div id="emailRecovery" style="display:none">
<div>Enter the mobile phone number you registered with</div>
<div><input type="tel" id="mobilePhone" /></div>
<div>Enter the postal code you registered with</div>
<div><input type="text" id="postalCode" /></div>
<div>
<button type="button" id="getEmailButton">GET EMAIL</button>
</div>
<div id="emailGetError"></div>
<div id="chooseCompany" style="display:none">
<select id="companies"></select>
</div>
</div>
<div id="code" runat="server" style="display:none">
<div>A text message with a verification code has been sent to <span id="msgPhone"></span>.<br />Enter the code you received below.</div>
<div><input type="text" id="codeInput" /></div>
<div id="codeInputError"></div>
<div>
<button type="button" id="sendCodeButton">SEND CODE</button>
</div>
</div>
<div id="changePass" style="display:none">
<div>Enter new password</div>
<div><input type="text" id="pwInput1" /></div>
<div id="pwInput1Error"></div>
<div>Enter new password again</div>
<div><input type="text" id="pwInput2" /></div>
<div id="pwInput2Error"></div>
<div>
<button type="button" id="changePassButton">UPDATE</button>
</div>
</div>
<div id ="ajaxResults" style="display:none"></div>
</form>
<script type="text/javascript" src="passwordReset.js"></script>
</body>
</html>
This part, $(divs[i]).attr("id"), comes back as undefined in the debugger. I'm trying to get the value of the id attribute of each div inside of #ajaxResults, and each div does have an id attribute. Something wrong with my syntax or understanding.
You're biggest problem is your for loop is checking 1 < divs.length instead of i < divs.length.
Use this instead:
for (i = 0; i < divs.length; i++) {
options += "<option value='" + $(divs[i]).attr("id") + "'>" + $(divs[i]).text() + "</option>";
}

Why does my function not run?

I'm trying to make a slogan game where the user inputs the company's name that uses the slogan. The games in early development and if missing a but my current code does not work.
<html land="en">
<head>
<title>Whats that ???</title>
<script>
function checkAnswer()
{
var answer = document.getElementById("answerInput");
var theAnswer = answer.value;
document.getElementById("correct/incorrent").innerHTML += theanswer;
}
</script>
</head>
<body>
<div id="game-container">
<div id="slogan">
<p>Das Auto</p>
</div>
<div id="answer">
<p>Answer<p>
<input id="answerInput" type="text">
<input type="button" value="Check" onClick="checkAnswer">
</div>
<div id="correct/incorrent">
Hello
</div>
</div>
Tnx Adam
Fixed syntax errors:
theanswer != theAnswer, missing camel case letter "A"
need to invoke function by () rather than just stating its reference checkAnswer
<html land="en">
<head>
<title>Whats that ???</title>
<script>
function checkAnswer() {
var answer = document.getElementById("answerInput");
var theAnswer = answer.value;
document.getElementById("correct/incorrent").innerHTML += theAnswer;
}
</script>
</head>
<body>
<div id="game-container">
<div id="slogan">
<p>Das Auto</p>
</div>
<div id="answer">
<p>Answer<p>
<input id="answerInput" type="text">
<input type="button" value="Check" onclick="checkAnswer()">
</div>
<div id="correct/incorrent">
Hello
</div>
</div>
</body>
</html>
The onclick event executes any javascript between the quotes. You were just referencing a function, not calling it.
onclick="checkAnswer()"
<html land="en">
<head>
<title>Whats that ???</title>
</head>
<body>
<div id="game-container">
<div id="slogan">
<p>Das Auto</p>
</div>
<div id="answer">
<p>Answer<p>
<input id="answerInput" type="text">
<input type="button" value="Check">
</div>
<div id="correct/incorrent">
Hello
</div>
</div>
<script>
var btn = document.getElementById("answerInput");
var ans = document.getElementById("correct/incorrent");
btn.onClick = function (){
var answer = document.getElementById("answerInput");
var theAnswer = answer.value;
ans.innerHTML += theAnswer;
}
</script>
</body>
</html>

Firebug returning odd error for one getElementById

I have the following lines of js
var select_container = "container_"+parts[2];
var get_container = document.getElementById(select_container);
The function this is part of is failing and when I look in firebug it returns get_container as undefined. I have checked select_container is the correct value and that there isn't a duplicate id on page.
This is called by an onclick event so I can't see waiting for the page to load being an issue (the result is same no matter how long I wait).
revelent html example:
<div id="container_0">
I'm stumped!
edit
This is all the Javascript from the parent functions
/*detects links in the form editor and uses them to adjust the layout*/
window.onload = function () {
clickDetection();
} /*detect clicks on interesting links*/
function clickDetection() {
var canvas = document.getElementById("content");
var dumbLinks = canvas.getElementsByTagName("a");
for (var i = 0; i < dumbLinks.length; i++) {
dumbLinks[i].onclick = function () {
clickRoute(this);
return false
};
}
} /*reroute click behaviour to correct function*/
function clickRoute(link_object) {
var linkId = link_object.getAttribute("id");
var linkParts = linkId.split("_");
if (linkParts[1] == "delete") {
delete_route(linkParts);
} else if (linkParts[1] == "new") {
new_route(linkParts);
}
}
function delete_route(parts) {
alert(parts);
if (parts[0] == "field") {
var select_container = "container_" + parts[2];
var get_container = document.getElementById(select_container);
document.removeChild(get_container);
} else if (parts[0] == "option") {
alert("delete a option");
}
}
full (typical) html (please note repeating sections have been cut for length and other details changed for secuity):
<!DOCTYPE HTML>
<html>
<head>
<!-- determines header content -->
<meta charset="utf-8" />
<meta name="description" content="Free Web tutorials" />
<meta name="keywords" content="HTML,CSS,XML,JavaScript" />
<script type="text/javascript" src="some.js"></script>
<title>Title of the document</title>
</head>
<body>
<div class="bignavblock"><p>nav link</p></div>
<div class="bignavblock"><p>nav linke</p></div>
<div class="bignavblock"><p>nav link</p></div>
<div class="bignavblock"><p>nav link</p></div>
<div class="bignavblock"><p>nav link</p></div>
<div class="bignavblock"><p>nav link</p></div>
<div id="content">
<h1>screen name</h1>
<form method="post" action="#this">
<label for="summary">Select an item to edit:<br></label>
<select name="summary" id="summary">
<option value="generic">generic</option>
<option value="updated">updated</option>
</select>
<input type="submit" name="summary_select" value="Select">
</form>
<h2>screen name</h2>
<div id="container_7">
<form method="post" action="#this">
<fieldset><legend>existing segment</legend>
<p><a id="field_delete_7" href="#">Delete field</a></p>
<label for="name_7">Field Name</label><input type=text id="name_7" name="name" value="Colour"><br>
<label for="type_7">Data type expected</label>
<select name="type" id="type_7">
<option value="name" >Name</option>
<option value="email" >Email Address</option>
<!-- cut for length -->
</select>
<p>Some text</p>
<label for="option_7_0">Option Value</label><input type=text id="option_7_0" name="option_7_0" value="Red">
<a id="option_delete_7_0" href="#">Delete option</a><br>
<label for="option_7_1">Option Value</label><input type=text id="option_7_1" name="option_7_1" value="Green">
<a id="option_delete_7_1" href="#">Delete option</a><br>
<label for="option_7_2">Option Value</label><input type=text id="option_7_2" name="option_7_2" value="Blue">
<a id="option_delete_7_2" href="#">Delete option</a><br>
<a id="option_new_7" href="#">Add new option</a>
<input type="submit" name="detail" value="Finish"></fieldset></form></div>
<p><a id="field_new" href="#">Add new field</a></p>
</div>
<!-- determines footer content -->
footer content
</body>
</html>
Change this:
document.removeChild(get_container);
to this:
get_container.parentNode.removeChild(get_container);
or if the containers are a direct descendant of body, then you could do this:
document.body.removeChild(get_container);

Categories