object is not a function - javascript

I made a pretty huge script for a form and everything works fine except that my select with onchange() doesnt work at all, but only in THIS script. If I try to do it on a blank page (just put a script tag, put my js inside of it, put my html code with my select tag, etc...everything works fine).
So my question is : Why is my function modele isn't working at all? Is there any kind of issu inside my head tag? Thx!
P.S. This is what I get in the console : Uncaught TypeError: object is not a function
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function modele(form) {
var x = form.marque.selectedIndex;
alert(x);
}
</script>
<style>
[...]
</style>
</head>
inside my body :
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post" id="credit">
[...]
<td><label for="marque">Marque :</label></td>
<td>
<select id="marque" name="marque" onChange="modele(this.form)">
<option></option>
<option>Acuras</option>
<option>Hondas</option>
<option></option>
<option></option>
</select>
</td>
<td><label for="modele">Modele :</label></td>
<td><select id="modele" name="modele">
<option></option>
</select>
</td>
[...]
</form>

The problem is that you've given the <select> element the id "modele". Change either that or the name of the function. The browser is overriding the binding of the function to the global name "modele" with a reference to the DOM node for the <select>.

There are two other objects with the name 'modele'. The first is the id of the second select tag and the second is the name of the second select is also 'modele'.
Try changing both to something else or change the name of the function to something else to make it work.

Related

javascript not displaying in jsp page

I wrote a code for retrieving data from database table and displaying it. The entire table is passed as arraylist through servlet to jsp page. Inside the jsp.. first only name is displayed in dropdown box. The objective was to choose a name from dropdown , and rest of the data corresponding to the name is displayed after the name is chosen. Arraylist has been passed correctly. Dropdown is working fine.
but javascript code to display the rest is not working. please help.code below iv shown only for one field. ie,for id.
output page with dropdown
<body>
<form action="Servletname" method="post" name="searchdatabase">
<%int i=0;
ArrayList<Cust> newlist=(ArrayList<Cust>) request.getAttribute("CusList");
if(newlist.size()>0){
%>
<table>
<tr>
<td> name :</td>
<td>
<select id="selectUsers" name="users" onChange='Choice();'>
<option> </option>
<%for(Cust c:newlist){ %>
<option value="<%=c.getCustId()%>"> <%=c.getName() %></option>
<%}%>
</select>
</td></tr>
<tr>
<td> id :</td>
<td>
<input type="text" id="ids" name="id" >
</td></tr>
</table>
</form>
<script type="text/javascript">
function Choice() {
//x = document.getElementById("users");
y = document.getElementById("selectUsers");
x=y.selectedIndex;
Cust c1= newlist.get(y.selectedIndex);
document.getElementById("ids").value =c.getCustId();
}
</script>
<%} %>
</body>
There are a few problems with your code.
First of all, scriptlets are deprecated and should be avoided. Use JSTL instead.
Secondly, your JavaScript code has no visibility of any of the variables used in your Java code. The Java is executed on the server, then some text (the HTML response) is sent to the browser. If it contains JavaScript, the browser runs the JavaScript.
I've rewritten what you're trying to achieve using JSTL instead of scriptlets for flow control and changing the JavaScript to get what you seem to be attempting:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<body>
<form action="Servletname" method="post" name="searchdatabase">
<c:if test="${not empty CusList}">
<table>
<tr>
<td> name :</td>
<td>
<select id="selectUsers" name="users" onChange='Choice();'>
<option> </option>
<c:forEach items="${CusList}" var="c">
<option value="${c.custId}"> <c:out value="${c.name}" /></option>
</c:forEach>
</select>
</td></tr>
<tr>
<td> id :</td>
<td>
<input type="text" id="ids" name="id" value="${CusList[0].custId}" >
</td></tr>
</table>
<!-- Note that I've moved the closing form tag and put it outside of this c:if block
because putting it here means it will only be output if your List is not empty -->
<script type="text/javascript">
function Choice() {
var y = document.getElementById("selectUsers");
var x = y.selectedIndex;
document.getElementById("ids").value = y.children[x].value;
}
</script>
</c:if>
</form><!-- outside of c:if because the opening tag is also outside of c:if -->
</body>
Edit:
I've just reread the question and realised that I haven't addressed your additional need of populating other inputs with other attributes of the customer.
As I said above, JavaScript has no visibility of data which is on the server, including your List of Customer objects. There are a few options available to you, but these are the two I would recommend:
Use HTML5 Data Attributes
HTML5 introduced data-* attributes for elements which can be accessed via your scripts. For example, you could do something like this:
<c:forEach items="${CusList}" var="c">
<option
value="${c.custId}"
data-surname="<c:out value="${c.surname}" />"
data-tel="<c:out value="${c.tel}" />"><!-- etc -->
<c:out value="${c.name}" />
</option>
</c:forEach>
Then in the JavaScript:
function Choice() {
var y = document.getElementById("selectUsers");
var x = y.selectedIndex;
var opt = y.children[x];
document.getElementById("ids").value = opt.value;
document.getElementById("surname").value = opt.dataset.surname;
document.getElementById("tel").value = opt.dataset.tel;
// etc
}
The downside of this approach is that if you have a large list with a high number of attributes you want to make available, that's a lot of text in the response.
Use AJAX
You could make an AJAX call in response to the select change and have the server return the customer data encoded in JSON format. The JavaScript would then decode the JSON and populate the elements with the correct values.
You'd need to research how to do this (there are plenty of tutorials available) but the steps in response to your select changing would be:
Disable the select box to prevent another change before you get the AJAX response from the server
Show some sort of throbber to indicate to the user that the data is being loaded
Make an AJAX request indicating the ID of the selected customer
The server responds with a JSON-encoded version of the corresponding customer object.
Update the inputs using the JSON data.
Hide the throbber and re-enable the select element.
The downside of this approach is that you'll need to learn how to properly use AJAX, including adding code to deal with errors (e.g., if the user loses network connectivity and you get no response from server to your AJAX request, you need to show an error message and have some sort of "retry" mechanism).

PHP Javascript cant access echoed element id outside php mode

Humble appologies if this is a stupid question but I cant for the life of me figure out what is wrong here.
I have an echoed element inside php mode:
echo'<select name="picks" id="winner">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
Now outside php
I try to do a basic javascript GET:
document.getElementById("winner");
However the elemnt is not accessible am I missing something here, is it not possible to get echoed elements Ids?
You should make sure your DOM has at least loaded before performing element selects. If you can use jQuery, then this is as easy as the following, and you can place this script in the head section, or anywhere in the body:
$(document).ready(function() {
// Perform any selects on the DOM
});
JS
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
// The DOM is loaded and ready to be selected
var select = document.getElementById("winner");
var optionText = select.options[select.selectedIndex].text;
var optionValue = select.options[select.selectedIndex].value;
});
</script>
Of course you can also perform DOM selects using jQuery:
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
// The DOM is loaded and ready to be selected
var optionText = $("#winner option:selected").text();
var optionValue = $("#winner option:selected").val();
});
</script>
Another possibility
If $row, $team1 or $team2 are not defined and you have PHP errors and notices turned on, then the HTML will render like so:
<select name="picks" id="winner"><b>E_NOTICE : </b> type 8 -- Undefined variable: row -- at line 4<br /><b>E_NOTICE : </b> type 8 -- Undefined variable: team1 -- at line 4<br />
<option value=""></option><b>E_NOTICE : </b> type 8 -- Undefined variable: row -- at line 5<br /><b>E_NOTICE : </b> type 8 -- Undefined variable: team2 -- at line 5<br />
<option value="" selected="selected"></option>
</select>
However, if you have PHP errors and warnings turned off, you would see something like this instead:
<select name="picks" id="winner">
<option value=""></option>
<option value="" selected></option>
</select>
If you are unable to access the value of options in your select HTML (because they are empty), this would be a good pace to start investigating.
Using JQUERY you can try following:
// I have used mouse down event for demo purpose.
$(document).delegate('#winner', 'mousedown', function ()
{
alert('hi');
});
Try accessing the value of the selected id
I am giving a demo fiddle
Demo fiddle
document.getElementById("winner").value;
Echoing JS codes is common but there are these possibilities:
1-You put document.getElementById("winner"); before php creating that element.
2-There is a syntax error in script tag which cause error and there for your select does not work.
since the php part will be available before page load you can simply do like this:
<?php
$row['team1']=1;$team1='India';$row['team2']=2; $team2='SA';
echo'<select name="picks" id="winner">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
?>
<script>
console.log(document.getElementById("winner"));//see this in console.
</script>

Display data in HTML form when loaded

N00b alert; I know enough to be dangerous, so forgive my ignorance...I've been through all of the related questions here and elsewhere, but I just can't seem to comprehend the answer that's surely included in the responses :-(
I'm posting a record id to a page where I want a form to display with the contents of the related record. I'm getting the record in correctly (confirmed using the alert) with this script in the HEAD section (jquery 1.9 is called as well):
<script type="text/javascript">
function getSelectedCustomer () {
...use the id to get the right record...
databaseAPI.callback = function() {
if (databaseAPI.error) {
alert("Database Error: " + databaseAPI.error);
}
else {
var customerRecord = databaseAPI.result;
alert("Test Callback: " + new String(customerRecord.full_name));
$("#quoteForm").load(customerRecord);
}
return;
};
databaseAPI.ajaxGet();
}
window.onload = getSelectedCustomer;
</script>
...and the form in the BODY to be loaded:
<form method="post" id="quoteForm" action="process_quote.php">
<table>
<tbody>
<tr>
<td>Name</td>
<td><input type="text" value="<?php $customerRecord['full_name']; ?>" name="full_name"></td>
</tr>
...other bits of the form...
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
I know I'm incorrectly munging various things together. Can someone please get me straightened out on what to do?
Michael's answer solved the INPUT fields in the form. Didn't mention I had SELECT fields as well:
<select size="0" name="email_sent">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
Changing INPUT to SELECT works.
What your missing is where code is being executed. The PHP code is being executed on the server, before being sent to the browser. The Javascript is then rendered by the browser. You can't pass variables back and forth between Javascript and PHP.
You want to inject the name with Javascript. I see you're already using jQuery, so the heavy lifting is already done for you. Remove the value="<?php $customerRecord['full_name']; ?>" from the PHP file, and replace $("#quoteForm").load(customerRecord); with $("#quoteForm input[name='full_name']").val(customerRecord.full_name);
Should work, might need some variation depending on your exact circumstances. At least it should put you down the right path.

JavaScript inside jstl iteration

I have the following codes:
<%int number=0;%>
<c:forEach var="row" items="${tAdmin.rows}" varStatus="totalRow" step="1">
<td><%=++number%></td>
<td>
<div id="content" style="table-layout:fixed; width:405px; word-wrap:break-word;">
<script language="JavaScript" type="text/JavaScript">
function load(){
var content='${row.content}';
document.getElementById("content").innerHTML=content;
document.getElementById("content").innerHTML=Utf8.decode(document.getElementById("content").innerHTML);
}
window.onload=load;
</script>
</div>
</td>
</c:forEach>
The problem is that it only shows the result of the last content instead of printing it out line by line according to number.
What you are creating, if you view the page source in the browser, would look something like this (note the ${row.content} will have already been replaced on the server):
<td>0<td>
<td>
<div id="content" style="table-layout:fixed; width:405px; word-wrap:break-word;">
<script language="JavaScript" type="text/JavaScript">
function load(){
var content='The first row content';
document.getElementById("content").innerHTML=content;
document.getElementById("content").innerHTML=
Utf8.decode(document.getElementById("content").innerHTML);
}
window.onload=load;
</script>
</div>
</td>
<td>1<td>
<td>
<div id="content" style="table-layout:fixed; width:405px; word-wrap:break-word;">
<script language="JavaScript" type="text/JavaScript">
function load(){
var content='Some different content';
document.getElementById("content").innerHTML=content;
document.getElementById("content").innerHTML=
Utf8.decode(document.getElementById("content").innerHTML);
}
window.onload=load;
</script>
</div>
</td>
<td>2<td>
<td>
<div id="content" style="table-layout:fixed; width:405px; word-wrap:break-word;">
<script language="JavaScript" type="text/JavaScript">
function load(){
var content='Yet some more content';
document.getElementById("content").innerHTML=content;
document.getElementById("content").innerHTML=
Utf8.decode(document.getElementById("content").innerHTML);
}
window.onload=load;
</script>
</div>
</td>
You're going to have many copies of function load() and many times where window.onload is assigned window.onload=load;
When this arrives at the browser and is interpreted, only the last definition of function load() will be in effect; only the last time you assign window.onload=load; means anything (because you keep replacing the value of window.onload) -- each redefinition of load() will replace the previous one - so only your last var content='${row.content}'; is ever executed.
In addition, you will have many <div> tags with the same id of "content" and that's not allowed.
The content of each of those <td><div>...</div></td> blocks can be set by the JSP/JSTL itself on the server -- there is no need to set the innerHTML via javascript.
You can use the totalRow varStatus that you set up to provide the number for the first <td> -- you don't need to increment your own counter.
You can use Expression Language (EL) to access the content value of each row.
Inline style="blah blah blah" sucks. Use that only if absolutely necessary.
Instead, put all this style in CSS targeting .contentbits:
style="table-layout:fixed; width:405px; word-wrap:break-word;"
becomes
.contentbits {
table-layout:fixed;
width:405px;
word-wrap:break-word;
}
The page fragment becomes much simpler:
<c:forEach var="row" items="${tAdmin.rows}" varStatus="totalRow" step="1">
<td>${totalRow}</td>
<td>
<div class="contentbits">${row.content}</div>
</td>
</c:forEach>
It's not the right way to do it, but a simple solution would be use addEventListener instead onload:
<%int number=0;%>
<c:forEach var="row" items="${tAdmin.rows}" varStatus="totalRow" step="1">
<td><%=++number%></td>
<td>
<div id="content<%=number%>" style="table-layout:fixed; width:405px; word-wrap:break-word;">
<script language="JavaScript" type="text/JavaScript">
window.addEventListener("load", function () {
var element = document.getElementById("content<%=number%>");
element.innerHTML=Utf8.decode('${row.content}');
}, true);
</script>
</div>
</td>
</c:forEach>
In fact your code is using only the last "onload" because, when loading the page, it will execute the javascript load callback only when finish full loading it. So, each time you loop is executed, it updates the load callback reference for the last one, so when onload is triggered, the last only will be executed.
But your code has other errors too. The content id, repeats at the code lot of times, that will make your div getElementById useless, because you have lot of ids that are equal. Ids must be unique to work property.
To finish, it's not a good pattern to mix your HTML with scripts inside, is better to have you logic file (javascript file) outside, then it can make changes in your code when finish to load, reading the html that was generated. You also can create data attribute in your div then read it by the javascript to manage all itens with a specific data attributes.
To keep it simple, I will add an example:
<%int number=0;%>
<c:forEach var="row" items="${tAdmin.rows}" varStatus="totalRow" step="1">
<td><%=++number%></td>
<td>
<div id="content<%=number%>" style="table-layout:fixed; width:405px; word-wrap:break-word;" data-content="${row.content}">
</div>
</td>
</c:forEach>
Now the script file (I'm using jQuery for this example works on any browser):
$(function() {
$("[data-content]").each(function(item) {
$(item).html(Utf8.decode(item.attr('data-content')));
});
});

Control not reaching to .js function

In my following code, I am calling function "Make Request" that is located in a separate .js file. But the control is not reaching to this function. I have also added the link to the related file.
<link rel="section" href="../Lib/ajaxhandler.js" type="text/javascript">
<td oncontrolselect="MakeRequest('inCategory','SELECT * FROM electioncategorymaster', 'ecid', 'ecname');">
<select id="inCategory" name="inCategory" class="entryFormInputBoxColor">
</select>
</td>
I want to make a call to the MakeRequest function when page is rendered. On which event I must call the function?
Your link to the script is wrong. The link tag is useful for e.g. stylesheets.
Your script tag should be like this:
<script src="../Lib/ajaxhandler.js" type="text/javascript"></script>
Also, you may want to catch the oncontrolselect event of the combo box instead of the td.
How about this...
<script src="../Lib/ajaxhandler.js" type="text/javascript"></script>
<td>
<select id="inCategory" name="inCategory" class="entryFormInputBoxColor"
onChange="MakeRequest('inCategory','SELECT * FROM electioncategorymaster', 'ecid', 'ecname');">
</select>
</td>

Categories

Resources