The problem probably lies on two events: onload, onclick (the event onload does work, but the onclick does not). How could I solve this problem in a best way to keep two of them running in the same code? Thanks for any suggestions.
const vacationPlaces = ['Praha','Vien','Munich'];
function backwards() {
for (let vacationSpotIndex = vacationPlaces.length - 1; vacationSpotIndex >= 0; vacationSpotIndex--) {
let showPlaces = vacationPlaces[vacationSpotIndex] + ", ";
let removeComma = showPlaces;
document.getElementById("resultMonthly").innerHTML += removeComma;
}
}
function forwards() {
for (let i = 0; i < vacationPlaces.length; i++) {
document.getElementById("resultDaily").innerHTML += vacationPlaces[i] + ", ";
}
}
function all() {
backwards();
forwards();
}
function click() {
document.getElementById("resultHourly").innerHTML = "hi";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Issue App</title>
<link rel="stylesheet" type="text/css" href="wageup.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body onload="all()">
<div class="container">
<h2>for loop</h2>
<div class="alert alert-success" role="alert" id="resultMonthly">
</div>
<div class="alert alert-info" role="alert" id="resultDaily">
</div>
<div onclick="click()" class="alert alert-warning" role="alert" id="resultHourly">
</div>
</div>
<!-- Scripts -->
<script src="http://chancejs.com/chance.min.js"></script>
<!-- Jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- JS -->
<script type="text/javascript" src="forloop.js"></script>
</body>
</html>
In the context of the onclick attribute, the function click is a native function. So your click handler is working, but it's calling the built-in click function, not your click function. You can fix that by renaming the function. For example, I named it showAlert:
const vacationPlaces = ['Praha','Vien','Munich'];
function backwards() {
for (let vacationSpotIndex = vacationPlaces.length - 1; vacationSpotIndex >= 0; vacationSpotIndex--) {
let showPlaces = vacationPlaces[vacationSpotIndex] + ", ";
let removeComma = showPlaces;
document.getElementById("resultMonthly").innerHTML += removeComma;
}
}
function forwards() {
for (let i = 0; i < vacationPlaces.length; i++) {
document.getElementById("resultDaily").innerHTML += vacationPlaces[i] + ", ";
}
}
function all() {
backwards();
forwards();
}
function showAlert() {
console.log('clicked')
document.getElementById("resultHourly").innerHTML = "hi";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Issue App</title>
<link rel="stylesheet" type="text/css" href="wageup.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"crossorigin="anonymous">
<!-- Scripts -->
<script src="http://chancejs.com/chance.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- <script type="text/javascript" src="forloop.js"></script> -->
</head>
<body onload="all()">
<div class="container">
<h2>for loop</h2>
<div class="alert alert-success" role="alert" id="resultMonthly"></div>
<div class="alert alert-info" role="alert" id="resultDaily"></div>
<div onclick="showAlert()" class="alert alert-warning" role="alert" id="resultHourly"></div>
</div>
</body>
</html>
Related
I am trying to call a simple javascript function from my JS page. But it's not working. Getting an error on calling my function by the event.
function searchWord() {
let w = document.getElementById("word")
const xhr = new XMLHttpRequest();
var word = `https://api.dictionaryapi.dev/api/v2/entries/en_US/${w.value}`
xhr.open('GET', word, true);
xhr.onload = function() {
let obj = JSON.parse(this.responseText)
html = ""
html += `<div class="card-body">
<h5 class="card-title" id="urWord">${obj[0].word}
<i class="fas fa-volume-up" id="audio" onclick="textAudio()"></i></h5>
<p class="card-text"><i class="muted">${obj[0].meanings[0].partOfSpeech} | ${obj[0].phonetics[0].text}</i></p>
<p class="card-text">${obj[0].meanings[0].definitions[0].definition}</p>
<p class="card-text"><i class="text-muted">- ${obj[0].meanings[0].definitions[0].example}.</i></p>
</div>`
let notesElm = document.getElementById("mean");
if (obj.length != 0) {
notesElm.innerHTML = html;
} else {
notesElm.innerHTML = `Nothing to show! Use "Add a Note" section above to add notes.`;
}
}
xhr.send();
}
function textAudio() {
console.log(obj[0].phonetics[0].text)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css" integrity="sha384-SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn2fk" crossorigin="anonymous">
<title>API :: Dictionary</title>
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" style="margin: auto;" href="index.html">
API-DICTIONARY
</a>
</div>
</nav>
<div class="container my-3">
<div class="input-group mb-3">
<input type="text" id='word' class="form-control" placeholder="Your Word">
<button class="btn btn-outline-secondary mx-1" type="button" id="SearchBtn" onclick="searchWord()">Search</button>
</div>
<div class="input-group mb-3" style="margin:auto" id="mean">
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script>
<script src="app.js"></script>
</html>
I am not getting any idea to solve this error. I hope anyone can provide a solution to this error. By the way, I tried many different things. Please anyone can help me?
I had that error before and what fixed it for me was using addEventListener instead of onclick, I still dont know what causes this error tho. I can give you an example on how to use it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script src="js/script.js"></script>
</head>
<body>
<h1 id="header-for-testing">Hello there!</h1>
</body>
</html>
and in the .js just do:
window.addEventListener('load', () => {
var header = document.getElementById("header-for-testing")
header.addEventListener("click", someFunction)
})
function someFunction(){
alert("this is a working event!")
}
Oh yea and dont actually use a header, I just used it for showing how to use addEventListener
Does this work for you?
I declared obj and textaudioText outside the functions.
Then used inline js for onclick and deleted testAudio() function.
var obj, textaudioText;
function searchWord() {
let w = document.getElementById("word");
const xhr = new XMLHttpRequest();
var word = `https://api.dictionaryapi.dev/api/v2/entries/en_US/${w.value}`
xhr.open('GET', word, true);
xhr.onload = function () {
var obj = JSON.parse(this.responseText)
var textaudioText = obj[0].phonetics[0].text;
console.log("textaudioText = " + textaudioText);
html = ""
html += `<div class="card-body">
<h5 class="card-title" id="urWord">${obj[0].word}
<i class="fas fa-volume-up" id="audio" onclick="console.log(${obj[0].phonetics[0].text});"></i></h5>
<p class="card-text"><i class="muted">${obj[0].meanings[0].partOfSpeech} | ${obj[0].phonetics[0].text}</i></p>
<p class="card-text">${obj[0].meanings[0].definitions[0].definition}</p>
<p class="card-text"><i class="text-muted">- ${obj[0].meanings[0].definitions[0].example}.</i></p>
</div>`
let notesElm = document.getElementById("mean");
if (obj.length != 0) {
notesElm.innerHTML = html;
} else {
notesElm.innerHTML = `Nothing to show! Use "Add a Note" section above to add notes.`;
}
}
xhr.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css"
integrity="sha384-SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn2fk" crossorigin="anonymous">
<title>API :: Dictionary</title>
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" style="margin: auto;" href="index.html">
API-DICTIONARY
</a>
</div>
</nav>
<div class="container my-3">
<div class="input-group mb-3">
<input type="text" id='word' class="form-control" placeholder="Your Word">
<button class="btn btn-outline-secondary mx-1" type="button" id="SearchBtn"
onclick="searchWord()">Search</button>
</div>
<div class="input-group mb-3" style="margin:auto" id="mean">
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.2/dist/umd/popper.min.js"
integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.min.js"
integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT"
crossorigin="anonymous"></script>
<script src="app.js"></script>
</html>
New to javascript, and I am attempting to make text appear below an image when the user mouses over it. For the HTML, I have created an empty sub tag with the id 'subtext' () below two images, and I am attempting to use a for loop, and if else statement to have a specific message occupy the subtext depending on which image is experiencing "mouseover".
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<link href="styles.css" rel="stylesheet">
</head>
<script>
document.addEventListener('DOMContentLoaded', function() {
let picture = document.querySelectorAll('.picture');
for (let i = 0; i <picture.length; i++) {
picture.addEventListener("mouseover", function () {
var text;
var pictureid = picture.getElementById();
if (pictureid === '#pic1') {
text = 'First response';
} else {
text = 'Second response';
}
document.getElementById('#subtext').innerHTML = text;
}
)};
});
</script>
<body>
<img src="IMG_1.jpg" width="300" height="400" class = picture id="pic1">
<img src="IMG_2.jpg" width="300" height="400" class = picture id ="pic2">
<sub id="subtext"></sub>
</body>
</html>
See here for error message - that I am missing a semicolon and have an unnecessary one at the same time
Your js code contains errors. Also, in the html structure, you did not wrap the class names in quotation marks. Like that:
class = picture
instead of for, I used the forEach() method in which I determined the current image:
picture.forEach(function (picture_current, index) {
picture_current.addEventListener("mouseover", function () {
...
document.addEventListener('DOMContentLoaded', function () {
let picture = document.querySelectorAll('.picture');
picture.forEach(function (picture_current, index) {
picture_current.addEventListener("mouseover", function () {
var text;
var pictureid = this.getAttribute('id');
if (pictureid === 'pic1') {
text = 'First response';
} else {
text = 'Second response';
}
document.querySelector('#subtext').innerHTML = text;
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<link href="styles.css" rel="stylesheet">
</head>
<body>
<img src="IMG_1.jpg" width="300" height="400" class="picture" id="pic1">
<img src="IMG_2.jpg" width="300" height="400" class="picture" id ="pic2">
<sub id="subtext"></sub>
</body>
</html>
a couple of typos but biggest problem was querySelectorAll returns an array
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<link href="styles.css" rel="stylesheet">
</head>
<body>
<img src="IMG_1.jpg" width="300" height="400" class = picture id="pic1">
<img src="IMG_2.jpg" width="300" height="400" class = picture id ="pic2">
<sub id="subtext"></sub>
<script>
document.addEventListener('DOMContentLoaded', function() {
let picture = document.querySelectorAll('.picture');
for (let i = 0; i <picture.length; i++) {
picture[i].addEventListener("mouseover", function () {
var text;
var pictureid = picture[i].id;
if (pictureid === 'pic1') {
text = 'First response';
} else {
text = 'Second response';
}
document.getElementById('subtext').innerHTML = text;
}
)};
});
</script>
</body>
</html>
I'm new for Angular and trying to do one exercise and result is not showing on browser.
(function() {
var app = angular.module('bus', []);
app.controller('BusContorller', function() {
this.busbarnd = basname;
});
var basname = {
name: 'tata',
yearprod: 2000,
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!-- container -->
<div class="container" ng-app="bus">
<!-- row -->
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<!-- Call controller -->
<div ng-controller="BusContorller as bus">
<p>Bus name : {{bus.busbarnd.name}}</p>
</div>
<!--// Call controller -->
</div>
</div>
<!-- // row end -->
</div>
<!-- // container -->
Kindly let me know what I'm doing wrong. I'm thinking I'm making mistake in calling controller.
Try like below
<!DOCTYPE html>
<html ng-app="bus">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<script>
var app = angular.module('bus',[]);
app.controller('BusContorller', function($scope){
$scope.busbarnd = $scope.basname;
$scope.basname = {
name: 'tata',
yearprod: 2000,
}
});
</script>
<body ng-controller="BusContorller">
<div ng-controller="BusContorller as bus">
<p>Bus name : {{busbarnd.name}}</p>
</div>
</body>
</html>
I'm trying to implement a slider using Javascript only (no external libraries like jQuery).
Here is my HTML file:
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Latest compiled and minified CSS -->
<script language="javascript" type="text/javascript" src="slider.js"></script>
<link rel="stylesheet" href="stylesheet.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="container main-container">
<div id="container">
<img id='slider-img' src='images/img1.png'>
<div id='left_holder'><img onclick="slider(-1)" class='left' src="images/arrow_left.png"></div>
<div id='right_holder'><img onclick="slider(1)" class='right' src="images/arrow_right.png"></div>
</div>
</div>
</body>
</html>
JS slider file:
(function() {
slider();
})();
function slider(element) {
var imagecount = 1;
var totalimage = 11;
var image = document.getElementById("slider-img");
imagecount = imagecount + element;
image.src = "images/img" + imagecount + ".png";
}
I'm getting an error at image.src cannot set property src of null because document.getElementById("slider-img"); can't get the element img of the html code. Anybody have some insight on this issue?
var imagecount = 1;
function slider(element) {
var totalimage = 11;
var image = document.getElementById("slider-img");
imagecount = imagecount < totalimage ? imagecount + Number(element) : 1;
if (imagecount < 1) {
imagecount = 1;
};
image.src = "images/img" + imagecount + ".png";
console.log(imagecount)
}
window.onload = function() {
slider(0)
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Latest compiled and minified CSS -->
<script language="javascript" type="text/javascript" src="slider.js"></script>
<link rel="stylesheet" href="stylesheet.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="container main-container">
<div id="container">
<img id='slider-img' src='images/img1.png'>
<div id='left_holder'>
<img onclick="slider(-1)" class='left' src="images/arrow_left.png">
</div>
<div id='right_holder'>
<img onclick="slider(1)" class='right' src="images/arrow_right.png">
</div>
</div>
</div>
</body>
</html>
change your markup so that the script is loaded right before the body ends
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="stylesheet.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="container main-container">
<div id="container">
<img id='slider-img' src='images/img1.png'>
<div id='left_holder'><img onclick="slider(-1)" class='left' src="images/arrow_left.png"></div>
<div id='right_holder'><img onclick="slider(1)" class='right' src="images/arrow_right.png"></div>
</div>
</div>
<script language="javascript" type="text/javascript" src="slider.js"></script>
</body>
</html>
so all the html is parsed when your script is executed
You can use the document.ready snippet from this answer:
What is the non-jQuery equivalent of '$(document).ready()'?
In your case:
function slider(element) {
var imagecount = 1;
var totalimage = 11;
var image = document.getElementById("slider-img");
imagecount = imagecount + element;
image.src = "images/img" + imagecount + ".png";
}
document.attachEvent("onreadystatechange", function(){
if (document.readyState === "complete"){
document.detachEvent( "onreadystatechange", arguments.callee );
slider();
}
});
The code at the bottom of the page dynamically populates a jQuery Mobile select menu. In addition to populating the menu I'd like to bind data to each menu item and assign a click handler. This is attempted with the following line.
menuItem.bind("click",{testdata: "test"}, clickHandler); $("#testMenu").append(menuItem); }
This approach has worked with jQuery Mobile lists in the past. Can anybody see what's going wrong?
Full Code:
<!DOCTYPE html>
<html xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="fbObj1.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.css"
/>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
/>
<link rel="stylesheet" href="http://jquerymobile.com/test/docs/buttons/css/themes/default/jquery.mobile.css"
/>
<link rel="stylesheet" href=http://jquerymobile.com/test/docs/buttons/_assets/css/jqm-docs.css "/>
<link rel="stylesheet " href="http://jquerymobile.com/test/docs/buttons/css/themes/default/jquery.mobile.css " />
</head>
<body>
<script>
function clickHandler(e) {
alert("click ");
alert(e.testdata);
};
$(document).ready(function() {
var int = 0;
for (int=0;int<=4;int=int+1)
{
var menuItem = $("<option id=''></option>");
menuItem.html("Item "+int); menuItem.attr('id',int);
//DATA BIND LINE
menuItem.bind("click",{testdata: "test"}, clickHandler);
//menuItem.on("click", {testdata: "test"}, clickHandler);
$("#testMenu").append(menuItem);
}
$("#testMenu").selectmenu('refresh');
$("#testMenu").selectmenu('open'); });
</script>
<div data-role="page">
<div data-role="header"></div>
<div data-role="content">
<div data-role="fieldcontain" id="testMenuFC" style="DISPLAY: none">
<select name="testMenu" id="testMenu" data-native-menu="false"></select>
</div>
</div>
</div>
</body>
change
menuItem.bind
to
$("#testMenu").bind
Edit :
function clickHandler(e) {
e.preventDefault();
alert($(this).val());
}
// i forgot to mentioned that for a "select menu" you should use "change" event instead of a "click"
$("#testMenu").on("change",
{testdata: "test"},
clickHandler);
});
Edit 2:
var i = 0;
function clickHandler(e) {
e.preventDefault();
$(":selected",$(this)).html(i).val(i).parent().selectmenu('refresh');
alert($(":selected",$(this)).val());
i++;
}
<link rel="stylesheet" href="http://jquerymobile.com/test/docs/buttons/css/themes/default/jquery.mobile.css" />
<link rel="stylesheet" href=http://jquerymobile.com/test/docs/buttons/_assets/css/jqm-docs.css"/>
<link rel="stylesheet" href="http://jquerymobile.com/test/docs/buttons/css/themes/default/jquery.mobile.css" />
</head>
<body>
<script>
$(document).ready(function() {
function clickHandler(e) {
var listItem = $(":selected",$(this));
alert(listItem.data("test").first);
alert(listItem.data("test").second);
};
var int = 0;
for (int=0;int<=4;int=int+1)
{
var menuItem = $("<option id=''></option>");
menuItem.html("Item "+int);
menuItem.attr('id',int);
menuItem.data("test", { first: int, second: "hello" })
$("#testMenu").append(menuItem);
}
$("#testMenu").on("change",{testdata: "test"}, clickHandler);
$("#testMenu").selectmenu('refresh');
$("#testMenu").selectmenu('open');
});
</script>
<div data-role="page">
<div data-role="header">
</div>
<div data-role="content">
<div data-role="fieldcontain" id="testMenuFC" style="DISPLAY: none">
<select name="testMenu" id="testMenu" data-native-menu="false">
</select>
</div>