val() returns [object Object] - javascript

Here is my script
<input type="text" id="teamleader-default" value="${foo.teamLeaderId}/${foo.teamLeaderFirstName} ${foo.teamLeaderLastName}" />
<script type="text/javascript">
$(document).ready(function(){
var teamleader = $('#teamleader-default').val();
var tl_details = teamleader.split("/");
$('#teamleader-default').prop('type', 'hidden');
$("#update").submit(function() {
if ($('#ParentDD :selected').text() == "Engineer") {
var tmp0 = $('#teamleader').val(tl_details[1]);
var tmp1 = $('#teamleaderId').val(tl_details[0]);
alert(tmp0);
alert(tmp1);
} else {
var tmp2 = $('#teamleader').val('');
var tmp3 = $('#teamleaderId').val(0);
alert(tmp2);
alert(tmp3);
}
});
});
</script>
The problem is that I can't assign a value for both the teamleader and the teamleader ID
$('#teamleader').val(tl_details[1]);
$('#teamleaderId').val(tl_details[0]);
instead the value it contains is just saying "Object object" like the one in this image:
Can anyone help me on how to assign a value for the team leader.
Again a big thanks for those who could help me.

I think the comments above have already answered the question quite well, if you want to know whether it is assgined successfully, you can use tm0.val().
By the way, using alert is not my choice to debug code like Js. Since you have chosen Chrome, you can get the advanced debug tool just press F12.You can get some tips on How to use Chrome DevTools
Happy coding~

Related

How to use array fill in javascript showing the text or number inputed by the user?

So one of my assignments is about that I should let the user type whatever he wants and then I have to fill the array with the input from the user, so it's basically could be number/s or text. I don't know if I should use getelementbyid.value or something else.
SO here´s what I have so far:
Fill1();
function Fill1() {
var text1 = document.getElementById("smth").value;
}
function prfunc() {
document.getElementById("answer").innerHTML = Fill1.fill(text1);
}
Type whatever you want: <input type="smth" id="smth"><br>
<button onclick="Fill1()">Fyll</button><br>
<div id="answer"></div>
Rando aside - I believe array.fill doesn't work in IE11, if you have any requirements around browser support. Dunno about any other browsers, just ran into that last week on a project.
Who uses IE11 nowadays? Apparently a few thousand of our customers.
Try
let array = Array(10);
function Fill1() {
array.fill(smth.value)
prfunc();
}
function prfunc() {
answer.innerText = array;
}
Type whatever you want: <input type="smth" id="smth"><br>
<button onclick="Fill1()">Fill</button><br>
<div id="answer"></div>

javascript function is adding data to screen but then being overridden by another function

My issue is related a function being invoked when a page is loaded, which removes the data returned by another function.
My issue
After an order is placed, the user inputs how much they wish to pay, following which their change will be calculated and displayed on the screen. I am able to see the amount of change due when I console.log(pay - rounded_total) (See JS code at end of post below).
However when I try change the div as opposed to logging to the console document.getElementById('change_due').innerHTML = (pay - rounded_total); it only remains on the screen for a matter of milliseconds before it disappears when the GET request is made again. I am sure this is because a get request is being triggered each time the document has loaded, so ideally I am wondering how best to structure my code to deal with this. I have played around with the code I currently have in every possible way at this stage, but still cannot fix the issue.
I am also aware that my class names should not begin with numbers, however my aim with this program is to improve my vanilla javascript, and get to terms with scope etc. in JS.
My code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<ul id="orderList">
<p class="4.75">Cafe Latte price = 4.75</p>
<p class="4.75">Flat White price = 4.75</p>
<p class="3.85">Cappucino price = 3.85</p>
</ul>
<div id="total_paid">Amount due: $0.00</div>
<div id="change_due"></div>
<form onsubmit="changeDue()">
<input type="text" id="uniqueID" />
<input type="submit">
</form>
<script src="js/getData.js"></script>
</body>
</html>
My JS code is as follows:
var rounded_total;
var change;
document.addEventListener("DOMContentLoaded", function(event) {
loadJSONDoc();
});
function loadJSONDoc()
{
var answer;
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
answer = JSON.parse(xmlhttp.responseText)
var items = answer[0].prices[0];
var total = 0;
for(var index in items) {
var node = document.getElementById("orderList");
var p = document.createElement('p');
var price = items[index];
p.setAttribute("class", price)
var textnode = document.createTextNode(index + " price = $" + price);
p.appendChild(textnode);
node.appendChild(p);
};
}
var total = 0;
var update = document.getElementsByTagName("p");
for(var i=0; i< update.length; ++i) {
update[i].onclick = function() {
var num = parseFloat(this.className).toFixed(2);
num = parseFloat(num)
total += num;
rounded_total = Math.round(total*100)/100;
document.getElementById("total_paid").innerHTML = rounded_total;
}
}
}
xmlhttp.open("GET","/items",true);
xmlhttp.send();
}
function changeDue(){
var pay = document.getElementById('uniqueID').value;
document.getElementById('change_due').innerHTML = (pay - rounded_total);
};
Again, to be clear on what I looking to implement, is that when a user has chosen their desired items, they then enter an amount into the input box, following which they submit will provide the amount of change due.
Any help on this would be greatly appreciated.
Thanks, Paul
There are different ways to fix this. But i am not able to understand as why you are using form post here and that too without the url?
you can update
function changeDue(){
...
return false; // this is avoid form submission
}
or
function changeDue(event){
...
// you can also use event.preventDefault() or stopPropagation() here. one of them should work.
}
But again both will stop the form from getting submitted to the server. When you will submit the form to the server, the current page will be refreshed and output of the form request will be displayed on the screen. Thats the reason why you are seeing it for a fraction of second. because your code updates the div and then form submit refreshes the page.
I really suggest you from good will nothing personal. Try to rewrite your code as I understand You are trying to success something with very very wrong structure.
Anyway You can try this or something similar...
function stopPost()
{
if (//something - you can skip if clause)
{
event.preventDefault();
return false;
}
}

passing javascript variable in document.getElementbyID

I know this is a silly question but i am not able to get the required result.I want to assign a javascript variable bck in document.getElementById(bck) .Everything is working fine i.e. alert displaying the correct value of variable bck but when i am using it inside the document.getElementbyID i am getting the following error:
document.getElementById(bck) is null
I googled it and looked in SO relevant topics also but got nothing helpful.
the value of backdropcontent[m][1] is Reden,also the value of selectedbg is Reden.
<script>
for ( var m=0;m<backdropcontent.length;m++) {
if(selectedbg==backdropcontent[m][1]){
var bck=backdropcontent[m][1]+'div1';
alert(bck);
document.getElementById(bck).style.display = "block";
document.getElementById(bck).style.top = "0px";
}
}
</script>
html part:
<div class="mcdropdown" id="Redendiv1" style="display:none;position:relative">
<a style="cursor: default !important">
<input type="text" name="reden1" id="reden1" style="background-image: url('<?php echo $mosConfig_live_site; ?>/templates/performitor/images/123.png');background-repeat: no-repeat;height:14px;width:130px !important;color:#BDBDBD;border: 1px solid #8e9daa;" disabled="disabled" value="Totaal" autocomplete="off"/>
</a>
</div>
please note that i dont want to alter the structure of my code so please dont suggest any major change.
Any help will be appreciated.Thanks.
The element with id backdropcontent[m][1]+'div1', does not exist
It's throwing error mostly because your element doesn't exist on the page yet. Move your <script> block below your code or use window.onload event.
window.onload = function(){
//your code
}
Or using jquery:
$(document).ready(function() {
// your code
});
you use the code in the following pattern
<script>
for ( var m=0;m<backdropcontent.length;m++) {
if(selectedbg==backdropcontent[m][1]){
var bck=backdropcontent[m][1]+'div1';
alert(bck);
document.getElementById("bck");.style.display = "block";
document.getElementById(bck).style.top = "0px";
}
}
</script>
May be this code helps you.

Calculating a number using a textbox

I've been trying to calculate a number using a number given by a user in a text box. I've been trying to use the following code. But when I try to test it, nothing happens. Is there something I'm missing? And is there a way that I can make the imprint variable global?
<form>
<p>How many products do you want
ingraved?<input id="imprint_amount" name="imprint_amount" type="text"/>
</p>
<p>Names to be Imprinted(one per
line)<TEXTAREA COLS=25 NAME="imprint_text" ROWS=5 WRAP=HARD style="resize:none;"></textarea>
</p>
<input onclick="imprint_price" type="button" value="Finish"/>
<p id="total_cost"></p>
</form>
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quality,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount');
imprint_total = $imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost') = "$" + imprint_total;
}
Thanks,
Traci
You will want to use the value property of that input element you are referencing in your variable:
… parseInt(imprint_quantity.value, 10);
For arbitrary HTML elements, you need to use textContent (or innerText to support old IE):
document.getElementById('total_cost').textContent = …;
Assigning to an expression as you did should have thrown a quite accurate exception, check your browser's error console for them.
Change your javascript to:
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quantity,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount').value;
imprint_total = imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost').innerHTML = imprint_total;
}
</script>
Working jsFiddle here http://jsfiddle.net/Zt38S/2/
In this line, you'll want to set the innerHTML of the element.
document.getElementById('total_cost').innerHTML = "$" + imprint_total;
This basically sets the text inside the <p></p> to be <p>$x.xx</p>.
And also this line should be
imprint_quantity = document.getElementById('imprint_amount').value;
which retrieves the value from the textbox.
Furthermore, when defining the variables, you wrote "quality". It should be
imprint_quantity,
imprint_quantity = document.getElementById('imprint_amount');
=
imprint_quantity = document.getElementById('imprint_amount').value();
Lemme know if that fixes it, a common enough mistake.

Getting the selected listValue of <s:select> in javascript

I am using tag of struts to display a list of items.
<s:select name="example" id="example" list="exampleList" listKey="exampleKey"
listValue="exampleValue" onchange="fun()"/>
Now I have a javascript function:
function fun()
{
var ex=document.getElementById("example");
alert(ex.value);
}
In this function I need to get the listValue of the selected item but when I'm using the above code, it just alerts me the listKey that I have selected. How can I get the listValue instead of listKey in the javascript function?
$(document).ready(function() {
$('#reminderTypeID').change(function()
{
var ex = document.getElementById("reminderTypeID");
var selTex = ex[$('#reminderTypeID').val()].text;
var selVal = ex[$('#reminderTypeID').val()].value;
alert(ex[$('#reminderTypeID').val()].text);
});
});
Try this (Worked for me):
function fun()
{
var ex = document.getElementById("example");
alert(ex.getAttribute('listValue'));
}
Edit
Added fiddle: http://jsfiddle.net/FranWahl/Ur6jT/2/
(Not sure why it won't work for you. In the fiddle it works.)
I ran into this same issue, and neither of the other answers was working for me. This is the solution that I found worked:
$(document).ready(function(){
$("#example").change(function(){
var options = document.getElementById("example").options;
var selectedIndex = document.getElementById("example").selectedIndex;
var selectedOptionText = options[selectedIndex].text;
var selectedOptionValue = options[selectedIndex].value;
console.log("Id of selected option is: " + selectedOptionValue);
console.log("Text of selected option is: " + selectedOptionText);
});
});
To further understand the issue, it helped to think about what HTML is created when the JSP is processed. The <s:select> will generate the following HTML:
<select id="example" name="example">
<option value="456">TextA</option>
...
</select>
Following OP's sample code, "456" would be derived from exampleKey and "TextA" from exampleValue. There would be such HTML <option> for each item in exampleList.
Note in my solution, I used the jQuery .change() function. However I also tried the solution with onchange="fun()", as the OP had done, and that worked too.
When I tried replacing document.getElementById("example") with $("#example"), the solution did not work.
Also helpful was reading this reference on <select> option selectedValue.

Categories