Can't change the value of an id within on function - javascript

I'd like to change the value of a <h2> with its id within a "on" function but it doesn't change.
Here's the code:
<div id="boardGame">
</div>
<script type="text/javascript">
json_dic = {"Too Much to Ask": "oHRjgi6sniY", "Sketchead": "GEfpkuCPjXs", "If You Were There, Beware": "ZVOwOzL9uDQ", "Plastic Tramp": "BiVXU2jt1Xo", "The Death Ramps": "p7cijGnXUJM", "Don't Sit Down 'Cause I've Moved Your Chair": "h1vYbHHhqYE", "R U Mine?": "VQH8ZTgna3Q", "2013": "O4vkZUC4VPA", "The Bakery": "P_D1Eqa2Lk4", "Potion Approaching": "Urw780t52zc", "Still Take You Home": "FKPKSK1nCKY", "Chun-Li's Spinning Bird Kick": "4lOdBxVS16o", "Come Together": "a-5tTz8flYI", "Snap Out of It": "PHoSRT2fNME", "Cigarette Smoker Fiona": "Wg89x455WK4", "Why'd You Only Call Me When You're High?": "6366dxFf-Os", "Brick by Brick": "qOTRx3ZqjjI", "Temptation Greets You Like Your Naughty Friend ": "VEWNOzgnmq0", "The Blond-O-Sonic Shimmer Trap": "EyBrLYN2Yok", "The Bad Thing": "3xTHjLf-ONg", "All My Own Stunts": "Er3r_J-mwII", "Love Is a Laserquest": "wxQVpRSxOZ0", "Dance Little Liar": "hf-B3Y3B0TQ", "Mardy Bum": "Lp1fQ51YZMM", "Stickin' to the Floor": "AQVMJkZGpSc", "Only Ones Who Know": "m-seRFY7-cw", "Crying Lightning": "fLsBJPlGIDU", "From the Ritz to the Rubble ": "givRh52Ic3A", "I.D.S.T.": "V6yORYEiLyU", "She's Thunderstorms": "tvHz5Rti0cU", "Catapult": "U3LsJMLWN2k", "Stop the World I Wanna Get Off with You": "3PyoxMSEHYI", "The Hellcat Spangled Shalalala": "dAlRXC19hmE", "Do I Wanna Know?": "bpOSxM0rNPM", "Knee Socks": "00bk5E7gecI", "That's Where You're Wrong": "tLOUVbemjro", "Leave Before the Lights Come On": "SEukS2YN9B8", "I Want It All": "SDTxuAEPfdY", "Secret Door": "ibyGhbvo94Q", "Suck It and See": "rjFGapDkSM0", "7": "R2t6vgC_OWw", "Brianstorm": "30w8DyEJ__0", "Baby I'm Yours": "EDLhMf6voq8", "Arabella": "Nj8r3qmOoZ8", "Old Yellow Bricks": "xLaeOrDmWQ4", "Don't Forget Whose Legs You're On": "qL0Z3Ly0CEw", "Riot Van": "j052-ROwPFM", "What If You Were Right the First Time?": "t2cFvzmqmwc", "Fire and the Thud": "VGlhSSP4nTk", "I Wanna Be Yours": "Y4NGoS330HE", "Mad Sounds": "J_-FwyoeV3E", "Fireside": "PG8yTUeptFU", "The Afternoon's Hat": "qbNKclt42Xc", "Reckless Serenade": "PY2FQ-LgmYo", "No Buses": "WK4wISbGvJw", "Electricity": "g-cukZ10j8A", "Little Illusion Machine (Wirral Riddler) ": "WlMzuzud8U4", "Piledriver Waltz": "njirT4N-JxU", "When the Sun Goes Down": "EqkBRVukQmE", "No. 1 Party Anthem": "83hFiC-siDs", "Evil Twin": "xwir-pg7WiA", "This House Is a Circus": "oDB-MGsWzQQ", "I Haven't Got My Strange": "a9yrz_psfLc", "Black Treacle": "1wznj4lD1Bs", "505": "ifZfUVp2chE", "Dangerous Animals": "qHe3E366_Po", "Perhaps Vampires Is a Bit Strong But..": "SjzOUf0AEiQ", "Fluorescent Adolescent": "ma9I9VBKPiw", "Library Pictures": "bmVerkoFPJU", "The View from the Afternoon": "PeQAZsyucbQ", "Despair in the Departure Lounge": "ZLS8ffCYN80", "I Bet You Look Good on the Dancefloor": "pK7egZaT3hs", "Bigger Boys and Stolen Sweethearts": "rLkikLrImnk", "Balaclava": "6LBCqG0YnTM", "Fake Tales of San Francisco": "ePg1tbia9Bg", "D Is for Dangerous": "zOlhvxPC3MQ", "Put Your Dukes Up John": "O8Wuv1WKldk", "My Propeller": "Z5vZovv8cPk", "Red Right Hand": "hcvGOUuDGXc", "One for the Road": "qN7gSMPQFss", "Joining the Dots": "wkvUl_l3o1c", "Red Light Indicates Doors Are Secured": "hdmR58BIHOg", "You and I ": "9zXkAaoBOLU", "Teddy Picker": "2A2XBoxtcUA", "Settle for a Draw": "IQ7NH2jcAAw", "Bad Woman ": "YnkJHU3qYIA", "Cornerstone": "LIQz6zZi7R0", "Fright Lined Dining Room": "qrqtD4TiO5c", "A Certain Romance": "WGyj5JyA5Ms", "If You Found This It's Probably Too Late": "SqKl1vcmvOU", "Who the Fuck Are Arctic Monkeys?": "oFeuKVkau6U", "Do Me a Favour": "lXJEDlLepD4", "You Probably Couldn't See for the Lights but You Were Staring Straight at Me": "j8iV3tK717s", "Dancing Shoes": "3aQELo7tXyI", "The Jeweller's Hands": "1rq0Ag15sAI", "Matador/Da Frame 2R": "DxoPxvJ0FNM", "Pretty Visitors": "4n7iaY22Do0", "You're So Dark": "6eoAwXkI3RA"}
var score = 0
var nb = 0
var iter = 0
var song
var start
var click
var listSongs = []
getHome()
$(document).on("click", '.calc_btn', function() {
iter++
$("#valueIter").html(iter+"/10")
if(iter == 10)
{
gameOver(score)
}
else
{
click = new Date()
time = (click.getTime() - start.getTime())/1000
if($(this).val() == song){
if(time <= 15)
score += parseInt((-1000/14)*time+929)
$("#valueScore").html(score)
$("#valueScore").css( "color", "green" )
}
else
{
$("#valueScore").html(score)
$("#valueScore").css( "color", "red" )
}
nb += 1
getSong()
}
})
function getHome()
{
score = 0
iter = 0
listSongs = []
$("#boardGame").html("<h2>Welcome to The Game of Monkeys</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' class='stres' value='Start' onclick='getSong()'></td></tr></tbody></table")
}
function getSong()
{
var keys = [];
for (var prop in json_dic) {
if (json_dic.hasOwnProperty(prop)) {
keys.push(prop);
}
}
song = keys[ keys.length * Math.random() << 0 ];
listSongs = [ song ]
url = json_dic[song]
while(listSongs.length <= 4)
{
var keys = [];
for (var prop in json_dic) {
if (json_dic.hasOwnProperty(prop)) {
keys.push(prop);
}
}
song_random = keys[ keys.length * Math.random() << 0 ];
listSongs.push(song_random)
}
$("#boardGame").html('<table class="calculatrice" id="calc"> '+
'<tbody>' +
'<tr>' +
'<td class="calc_td_btn">' +
'<div style="position:relative;width:380px;height:25px;overflow:hidden;">' +
'<div id="yt_video" style="position:absolute;top:-276px;left:-5px">' +
'</div>' +
'</div>' +
'</td>' +
'</tr>');
for(var i = 0; i <= 4; i++)
{
var randomIndex = Math.floor(Math.random() * listSongs.length);
var randomString = listSongs[randomIndex];
$("#boardGame").append('<tr>'+
'<td class="calc_td_btn">' +
'<input type="button" class="calc_btn" value="'+randomString+'">' +
'</td>' +
'</tr>')
var index = listSongs.indexOf(randomString);
listSongs.splice(index, 1);
}
$("#boardGame").append('<tr>' +
'<td class="calc_td_btn">' +
'<h2 id="valueScore">0 points</h2>' +
'<h2 id="valueIter">0/10</h2>' +
'<input type="button" class="stres" onclick="getHome()" value="Restart">' +
'</td>' +
'</tr>' +
'</tbody>' +
'</table>')
var nb = getRandomInt(0,100)
$("#yt_video").html("<iframe src='https://www.youtube.com/embed/"+url+"?autoplay=0&start="+nb+"' id='yt_video' width='380' height='300'></iframe>")
start = new Date()
}
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function gameOver(score){
$("#boardGame").html("<h2>You scored "+score+" points</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' onclick='getHome()' class='stres' value='Restart'></td></tr></tbody></table")
}
</script>
</body>
</html>
And it's the value of #valueScore that doesn't want to change. I think it it a scope problem but I can't get my way around it.
I can the value of #valueScore in the console or if I put the piece of code $("#valueScore").html(score) somewhere else in my JavaScript.
EDIT : added the whole code

The problem is that you're blowing away the DOM of all the elements at line 93-106 and you're re-creating them all. So the element that you're setting the score on is being destroyed and replaced with a completely different <h2>.
Instead of destroying everything (line 82 is where you replace the html of '#boardGame') you need to use JQuery to modify the buttons that already exist to give them the names of the song list.
As an alternative, try doing this:
Give all the multiple-choice buttons a class: '.choice_button'
Put a <div id="button_wrapper"> around all the buttons so that you have something to insert the new buttons into.
Instead of replacing the HTML for '#boardGame' simply destroy all the buttons: $('#button_wrapper .choice_button').remove()
Now you can insert the new buttons using that for loop just like you're doing on line 93
Now $('#valueScore') hasn't been blown away so the score should remain.
I've modified your code to get it to where I think it's what you're after:
<div id="boardGame">
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
json_dic = {"Too Much to Ask": "oHRjgi6sniY", "Sketchead": "GEfpkuCPjXs", "If You Were There, Beware": "ZVOwOzL9uDQ", "Plastic Tramp": "BiVXU2jt1Xo", "The Death Ramps": "p7cijGnXUJM", "Don't Sit Down 'Cause I've Moved Your Chair": "h1vYbHHhqYE", "R U Mine?": "VQH8ZTgna3Q", "2013": "O4vkZUC4VPA", "The Bakery": "P_D1Eqa2Lk4", "Potion Approaching": "Urw780t52zc", "Still Take You Home": "FKPKSK1nCKY", "Chun-Li's Spinning Bird Kick": "4lOdBxVS16o", "Come Together": "a-5tTz8flYI", "Snap Out of It": "PHoSRT2fNME", "Cigarette Smoker Fiona": "Wg89x455WK4", "Why'd You Only Call Me When You're High?": "6366dxFf-Os", "Brick by Brick": "qOTRx3ZqjjI", "Temptation Greets You Like Your Naughty Friend ": "VEWNOzgnmq0", "The Blond-O-Sonic Shimmer Trap": "EyBrLYN2Yok", "The Bad Thing": "3xTHjLf-ONg", "All My Own Stunts": "Er3r_J-mwII", "Love Is a Laserquest": "wxQVpRSxOZ0", "Dance Little Liar": "hf-B3Y3B0TQ", "Mardy Bum": "Lp1fQ51YZMM", "Stickin' to the Floor": "AQVMJkZGpSc", "Only Ones Who Know": "m-seRFY7-cw", "Crying Lightning": "fLsBJPlGIDU", "From the Ritz to the Rubble ": "givRh52Ic3A", "I.D.S.T.": "V6yORYEiLyU", "She's Thunderstorms": "tvHz5Rti0cU", "Catapult": "U3LsJMLWN2k", "Stop the World I Wanna Get Off with You": "3PyoxMSEHYI", "The Hellcat Spangled Shalalala": "dAlRXC19hmE", "Do I Wanna Know?": "bpOSxM0rNPM", "Knee Socks": "00bk5E7gecI", "That's Where You're Wrong": "tLOUVbemjro", "Leave Before the Lights Come On": "SEukS2YN9B8", "I Want It All": "SDTxuAEPfdY", "Secret Door": "ibyGhbvo94Q", "Suck It and See": "rjFGapDkSM0", "7": "R2t6vgC_OWw", "Brianstorm": "30w8DyEJ__0", "Baby I'm Yours": "EDLhMf6voq8", "Arabella": "Nj8r3qmOoZ8", "Old Yellow Bricks": "xLaeOrDmWQ4", "Don't Forget Whose Legs You're On": "qL0Z3Ly0CEw", "Riot Van": "j052-ROwPFM", "What If You Were Right the First Time?": "t2cFvzmqmwc", "Fire and the Thud": "VGlhSSP4nTk", "I Wanna Be Yours": "Y4NGoS330HE", "Mad Sounds": "J_-FwyoeV3E", "Fireside": "PG8yTUeptFU", "The Afternoon's Hat": "qbNKclt42Xc", "Reckless Serenade": "PY2FQ-LgmYo", "No Buses": "WK4wISbGvJw", "Electricity": "g-cukZ10j8A", "Little Illusion Machine (Wirral Riddler) ": "WlMzuzud8U4", "Piledriver Waltz": "njirT4N-JxU", "When the Sun Goes Down": "EqkBRVukQmE", "No. 1 Party Anthem": "83hFiC-siDs", "Evil Twin": "xwir-pg7WiA", "This House Is a Circus": "oDB-MGsWzQQ", "I Haven't Got My Strange": "a9yrz_psfLc", "Black Treacle": "1wznj4lD1Bs", "505": "ifZfUVp2chE", "Dangerous Animals": "qHe3E366_Po", "Perhaps Vampires Is a Bit Strong But..": "SjzOUf0AEiQ", "Fluorescent Adolescent": "ma9I9VBKPiw", "Library Pictures": "bmVerkoFPJU", "The View from the Afternoon": "PeQAZsyucbQ", "Despair in the Departure Lounge": "ZLS8ffCYN80", "I Bet You Look Good on the Dancefloor": "pK7egZaT3hs", "Bigger Boys and Stolen Sweethearts": "rLkikLrImnk", "Balaclava": "6LBCqG0YnTM", "Fake Tales of San Francisco": "ePg1tbia9Bg", "D Is for Dangerous": "zOlhvxPC3MQ", "Put Your Dukes Up John": "O8Wuv1WKldk", "My Propeller": "Z5vZovv8cPk", "Red Right Hand": "hcvGOUuDGXc", "One for the Road": "qN7gSMPQFss", "Joining the Dots": "wkvUl_l3o1c", "Red Light Indicates Doors Are Secured": "hdmR58BIHOg", "You and I ": "9zXkAaoBOLU", "Teddy Picker": "2A2XBoxtcUA", "Settle for a Draw": "IQ7NH2jcAAw", "Bad Woman ": "YnkJHU3qYIA", "Cornerstone": "LIQz6zZi7R0", "Fright Lined Dining Room": "qrqtD4TiO5c", "A Certain Romance": "WGyj5JyA5Ms", "If You Found This It's Probably Too Late": "SqKl1vcmvOU", "Who the Fuck Are Arctic Monkeys?": "oFeuKVkau6U", "Do Me a Favour": "lXJEDlLepD4", "You Probably Couldn't See for the Lights but You Were Staring Straight at Me": "j8iV3tK717s", "Dancing Shoes": "3aQELo7tXyI", "The Jeweller's Hands": "1rq0Ag15sAI", "Matador/Da Frame 2R": "DxoPxvJ0FNM", "Pretty Visitors": "4n7iaY22Do0", "You're So Dark": "6eoAwXkI3RA"}
var score = 0
var nb = 0
var iter = 0
var song
var start
var click
var listSongs = []
getHome()
$(document).on("click", '.calc_btn', function() {
iter++
$("#valueIter").html(iter+"/10")
if(iter == 10)
{
gameOver(score)
}
else
{
click = new Date()
time = (click.getTime() - start.getTime())/1000
if($(this).val() == song){
if(time <= 15)
score += parseInt((-1000/14)*time+929)
$("#valueScore").html(score)
$("#valueScore").css( "color", "green" )
}
else
{
$("#valueScore").html(score)
$("#valueScore").css( "color", "red" )
}
nb += 1
getSong()
return false;
}
})
function getHome()
{
score = 0
iter = 0
listSongs = []
$("#boardGame").html(
'<h2>Welcome to The Game of Monkeys</h2>'+
'<table class="calculatrice" id="calc">' +
'<tbody>' +
'</tbody>' +
'</table>' +
'<div id="gameButtons" style="display: none;">' +
'<h2 id="valueScore">0 points</h2>' +
'<h2 id="valueIter">0/10</h2>' +
'<input type="button" class="stres" onclick="getHome()" value="Restart">' +
'</div>' +
'<input type="button" class="stres" value="Start" onclick="getSong()">'
)
}
function getSong()
{
var keys = [];
for (var prop in json_dic) {
if (json_dic.hasOwnProperty(prop)) {
keys.push(prop);
}
}
song = keys[ keys.length * Math.random() << 0 ];
listSongs = [ song ]
url = json_dic[song]
while(listSongs.length <= 4)
{
var keys = [];
for (var prop in json_dic) {
if (json_dic.hasOwnProperty(prop)) {
keys.push(prop);
}
}
song_random = keys[ keys.length * Math.random() << 0 ];
listSongs.push(song_random)
}
// adds the music player, of course
$('#calc tbody').html (
'<tr>' +
'<td class="calc_td_btn">' +
'<div style="position:relative;width:380px;height:25px;overflow:hidden;">' +
'<div id="yt_video" style="position:absolute;top:-276px;left:-5px">' +
'</div>' +
'</div>' +
'</td>' +
'</tr>');
// adds the multiple choice buttons
for(var i = 0; i <= 4; i++)
{
var randomIndex = Math.floor(Math.random() * listSongs.length);
var randomString = listSongs[randomIndex];
$("#calc tbody").append('<tr>'+
'<td class="calc_td_btn">' +
'<input type="button" class="calc_btn" value="'+randomString+'">' +
'</td>' +
'</tr>')
var index = listSongs.indexOf(randomString);
listSongs.splice(index, 1);
}
// shows the score and the restart button
$('#gameButtons').show();
var nb = getRandomInt(0,100)
$("#yt_video").html("<iframe src='https://www.youtube.com/embed/"+url+"?autoplay=0&start="+nb+"' id='yt_video' width='380' height='300'></iframe>")
start = new Date()
}
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function gameOver(score){
$("#boardGame").html("<h2>You scored "+score+" points</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' onclick='getHome()' class='stres' value='Restart'></td></tr></tbody></table")
}
</script>
</body>
</html>

Oh I think I see the problem. You do not need to use the .html function.
Using jQuery:
$("#valueIter").val(iter+"/10");
$("#valueScore").val(score);
The html function is used to populate an element with raw html. The difference here is that jQuery provides .val() and .text() as getters and setters for any element which equate to the javascript equivelent of
element.value = score;

Related

Change image and quote on a click?

I'm creating a quick little page. I'm just learning JavaScript and it's taking some getting used to. I was able to create a page that changes quotes when the image is clicked. Now, I want the image to change with the quotes. So it will be: click on image 1, and image 2 will appear with quote 2. Click on image 2, and image 3 will appear with quote 3.
This is a pretty simple task but I have not been able to find an easy solution. I've spent a couple hours on this, which is sort of depressing.
Here's the page: https://aprilehrlich.github.io/dataint/
Following is what I've got in HTML:
<!DOCTYPE html>
<html>
<head>
<title>Ida B. Wells</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<img id="MainProductImage"" src="https://i.ytimg.com/vi/pUMKFP4p2Lo/maxresdefault.jpg" width="500px"" id="myImg">
<h1>“Quote 1.”</h1>
<p>- Ida B. Wells</p>
</body>
</html>
JavaScript:
$(document).ready(function() {
var quote1 = "“Quote 1.”";
var quote2 = "“Quote 2”";
var quote3 = "“Quote 3”";
var quote4 = "“Quote 4”";
var quote5 = "“Quote 5”";
var quote6 = "“Quote 6”";
var quote7 = "“Quote 7”";
var quote8 = "“Quote 8”";
var quote9 = "“Quote 9”";
var quote10 = "“Quote 10”";
$("img").click(function() {
var currentQuote = $("h1").text();
$("h1").fadeOut(0);
if (currentQuote == quote1) {
$("h1").text(quote2);
}
if (currentQuote == quote2) {
$("h1").text(quote3);
}
if (currentQuote == quote3) {
$("h1").text(quote4);
}
if (currentQuote == quote4) {
$("h1").text(quote5);
}
if (currentQuote == quote5) {
$("h1").text(quote6);
}
if (currentQuote == quote6) {
$("h1").text(quote7);
}
if (currentQuote == quote7) {
$("h1").text(quote8);
}
if (currentQuote == quote8) {
$("h1").text(quote9);
}
if (currentQuote == quote9) {
$("h1").text(quote10);
}
$("h1").fadeIn(1000);
});
})
You have to use the attr (attribute) function to change the src element. Here's an example. I made your code a little bit more dynamic so you can set as many quotes as you wish without changing your code:
HTML:
<img id="MainProductImage" src="https://s-media-cache-ak0.pinimg.com/564x/2a/b4/e7/2ab4e74ad637f9c8ecb792b8b7d605a6.jpg" id="myImg" data-current-quote="0">
<h1>“Quote 1.”</h1>
<p>- Ida B. Wells</p>
Javascript:
$(document).ready(function(){
//Quotes/Image Array
var quotes = [
{ quote: "Quote1", img: "https://s-media-cache-ak0.pinimg.com/564x/2a/b4/e7/2ab4e74ad637f9c8ecb792b8b7d605a6.jpg"},
{ quote: "Quote2", img: "https://s-media-cache-ak0.pinimg.com/564x/af/52/03/af5203d09a0be9c9e655786c88c1d8b7.jpg"},
{ quote: "Quote3", img: "https://s-media-cache-ak0.pinimg.com/564x/04/37/3c/04373c4f98797b202d13b9882e137690.jpg"}
];
$("img").click(function(){
var img = $("#MainProductImage"),
//We look for the next quote, if it's the last we go to the beginning
currentQuote = img.data("current-quote") === quotes.length -1 ? 0 : img.data("current-quote") + 1,
nextQuote = quotes[currentQuote];
//Set the current quote index in a data attribute
img.data("current-quote", currentQuote);
$("h1").fadeOut(0);
//Change the text
$("h1").text(nextQuote.quote);
//Change the image
img.attr("src", nextQuote.img);
});
});
Fiddle: https://jsfiddle.net/p2bus29y/2/
var data = [
{
"CategoryID": 1,
"CategoryName": "Soler Power Plant",
"CategoryProducts": [
{
"ID": 1,
"Name": 'Commercial Solar Power Plant',
"SubTitle": 'Eco, Eco Friendly, Energy, Green, Solar',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": 'Having a pre-determined quality administration system, we are thoroughly involved in delivering Commercial Solar Power Plant.',
"ImageUrl": 'assets/images/Products/Sola-power-plant.jpg',
},
{
"ID": 2,
"Name": 'Industrial Solar Power Plants',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": 'So as to become a preferential business name, we are thoroughly engrossed in shipping an inclusive collection of Industrial Solar Power Plants.',
"ImageUrl": 'assets/images/Products/Industrial_Solar_Power_Plants.jpg',
},
{
"ID": 3,
"Name": 'On Grid Solar Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 1.1 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of On Grid Solar Plant. To sustain the quality, our products are made under the guidance of industry certified professionals.",
"ImageUrl": 'assets/images/Products/On_Grid_Solar_Plant.jpg',
},
{
"ID": 4,
"Name": 'On Grid Solar Power Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of On Grid Solar Power Plant. To sustain the quality, our products are made under the guidance of industry top professionals.",
"ImageUrl": 'assets/images/Products/On_Grid_Solar_Power_Plant.jpg',
},
{
"ID": 5,
"Name": 'Solar Power Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of Solar Power Plant. To sustain the quality, our products are made under the guidance of industry certified professionals.",
"ImageUrl": 'assets/images/Products/Solar_Power_Plant.jpg',
},
]
}
]
function GetProducts() {
var products = data;
$.each(products, function () {
//var product = products.filter(filterByID)
var product = this;
$('#ProductDetails').append('<h2 class="text-center">' + this.CategoryName + '</h2>');
var details = product;
$.each(details.CategoryProducts, function () {
tempData = tempData + '<div class="col-md-4 col-sm-6">' +
'<div class="project-box">' +
'<div class="frame-outer">' +
'<div class="frame">' +
'<img style="width:350px;" src="' + this.ImageUrl + '" class="attachment-340x220 size-340x220 wp-post-image" alt="">' +
'</div>' +
'</div>' +
'<div class="text-box">' +
'<h3><a>' + this.Name + '</a></h3>' +
'<div class="tags-row">' +
'<a class="link">' + this.SubTitle + '</a>' +
'</div>' +
'<p>' + this.Description + '</p>' +
//'More Details' +
'</div>' +
'</div>' +
'</div>';
});
$('#ProductDetails').append('<div class="row">' + tempData + '</div>');
tempData = '';
});
}
Here, it's my own code may be it helps you. It does not belong to your code but you can understand and maybe you need to do like this
I have created an array with the quote and image sources. I have incremented a counter to define the index of the array. I have also made it so the quote fades back in once everything is done, so the text doesn't change until it has faded out.
$(document).ready(function(){
// set array of quotes and images
var content = [
["“Quote 1.”", "https://i.ytimg.com/vi/pUMKFP4p2Lo/maxresdefault.jpg"],
["“Quote 2.”", "http://www.stevensegallery.com/460/300"],
["“Quote 3.”", "http://www.stevensegallery.com/300/200"],
["“Quote 4.”", "http://www.stevensegallery.com/460/300"],
["“Quote 5.”", "http://www.stevensegallery.com/300/200"],
["“Quote 6.”", "http://www.stevensegallery.com/284/196"],
["“Quote 7.”", "http://www.stevensegallery.com/300/200"],
["“Quote 8.”", "http://www.stevensegallery.com/460/300"],
["“Quote 9.”", "http://www.stevensegallery.com/300/200"],
["“Quote 10.”", "http://www.stevensegallery.com/284/196"],
];
// set counter to 1
var count = 1;
$("img").click(function(){
// check is end of array reached and start from beginning
count == content.length ? count = 0 : "";
// fade h1 out
$("h1").fadeOut(500, function() {
// use counter to get the correct index of array to change the h1 to the relevent quote
$("h1").text(content[count][0]);
// use counter to get the correct index of array to change the h1 to the relevent image source
$("img").attr("src", content[count][1]);
// fade h1 back in after everything else is done
$("h1").fadeIn(500);
// increment count by 1
count++;
});
});
});
<img id="MainProductImage"" src="https://i.ytimg.com/vi/pUMKFP4p2Lo/maxresdefault.jpg" width="500px"" id="myImg">
<h1>“Quote 1.”</h1>
<p>- Ida B. Wells</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

have populated radio buttons, want to use submit button to print the value out

Is there a way to grab the values from the radio buttons? say it gets populated in the radio button and the options are Abuelos, Boogie Burger, Pad Thai, Coalition Pizza, Wild Eggs. Is there a way I can pull those values out and have it print out after hitting a submit button?
I also don't want the value to be redirected to another page. I just want it to print out below the submit button. I also don't want the user to be able to select a value after they hit the submit button
I am trying to make a voting poll where options are taken from multiple arrays and then someone can pick a value from the radio button and hit a submit button with their option printed out. That way the user can tell what they voted for.
part of the HTML code:
<form action="" id="food-form"></form>
Javascript code:
var mexicanFood = ["Caliente Mexican", "Abuelos", "Luciana's"],
asianFood = ["Omoni Korean", "Super Bowl Pho", "Sichuan Chinese", "Tian Fu Asian Bistro"],
americanFood = ["Boogie Burger", "City Barbeque", "The North End BBQ", "Wolfies Grill", "Bubs", "Fire on the Monon"];
pizza = ["Coalition Pizza", "Mackenzie River Pizza, Grill & Pub", "Bazbeaux Pizza", "Mellow Mushroom"]
thaiFood = ["Pad Thai", "Jasmine Thai", "Thai Orchid"]
notCategory = ["Jamaican Reggae Grill", "Mudbugs", "Yats", "Kolache Factory", ]
breakfast = ["Wild Eggs", "Egg and I", "Another Broken Egg Cafe", "Cafe Patachou"]
function createRandomArray(arraySize) {
var allFoods = mexicanFood.concat(asianFood).concat(americanFood).concat(pizza).concat(thaiFood).concat(notCategory).concat(breakfast),
randomFoods = [];
if (arraySize <= allFoods.length) {
randomFoods = [
mexicanFood[getRandomArrayIndex(mexicanFood)],
asianFood[getRandomArrayIndex(asianFood)],
americanFood[getRandomArrayIndex(americanFood)],
pizza[getRandomArrayIndex(pizza)],
thaiFood[getRandomArrayIndex(thaiFood)],
notCategory[getRandomArrayIndex(notCategory)],
breakfast[getRandomArrayIndex(breakfast)]
]; // at least one from each
// remove the ones that were initially added from each
allFoods.splice(allFoods.indexOf(randomFoods[0]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[1]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[2]), 1);
for (var i = 0; i < arraySize - 3; i++) {
var randomIndex = getRandomArrayIndex(allFoods);
randomFoods.push(allFoods[randomIndex]);
allFoods.splice(randomIndex, 1);
}
return randomFoods;
}
return allFoods; // requesting more items of food than the amount available, so just add them all
}
function getRandomArrayIndex(array) {
return Math.floor(Math.random() * array.length);
}
var randomFoods = createRandomArray(5);
for (var i = 0; i < randomFoods.length; i++) {
document.getElementById('food-form').innerHTML += '<input type="radio" name="food" value="' + randomFoods[i] + '"> ' + randomFoods[i] + '<br>';
}
You can use document.querySelector('input[name=food]:checked').value to get the selected value.
var mexicanFood = ["Caliente Mexican", "Abuelos", "Luciana's"],
asianFood = ["Omoni Korean", "Super Bowl Pho", "Sichuan Chinese", "Tian Fu Asian Bistro"],
americanFood = ["Boogie Burger", "City Barbeque", "The North End BBQ", "Wolfies Grill", "Bubs", "Fire on the Monon"];
pizza = ["Coalition Pizza", "Mackenzie River Pizza, Grill & Pub", "Bazbeaux Pizza", "Mellow Mushroom"]
thaiFood = ["Pad Thai", "Jasmine Thai", "Thai Orchid"]
notCategory = ["Jamaican Reggae Grill", "Mudbugs", "Yats", "Kolache Factory", ]
breakfast = ["Wild Eggs", "Egg and I", "Another Broken Egg Cafe", "Cafe Patachou"]
function createRandomArray(arraySize) {
var allFoods = mexicanFood.concat(asianFood).concat(americanFood).concat(pizza).concat(thaiFood).concat(notCategory).concat(breakfast),
randomFoods = [];
if (arraySize <= allFoods.length) {
randomFoods = [
mexicanFood[getRandomArrayIndex(mexicanFood)],
asianFood[getRandomArrayIndex(asianFood)],
americanFood[getRandomArrayIndex(americanFood)],
pizza[getRandomArrayIndex(pizza)],
thaiFood[getRandomArrayIndex(thaiFood)],
notCategory[getRandomArrayIndex(notCategory)],
breakfast[getRandomArrayIndex(breakfast)]
]; // at least one from each
// remove the ones that were initially added from each
allFoods.splice(allFoods.indexOf(randomFoods[0]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[1]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[2]), 1);
for (var i = 0; i < arraySize - 3; i++) {
var randomIndex = getRandomArrayIndex(allFoods);
randomFoods.push(allFoods[randomIndex]);
allFoods.splice(randomIndex, 1);
}
return randomFoods;
}
return allFoods; // requesting more items of food than the amount available, so just add them all
}
function getRandomArrayIndex(array) {
return Math.floor(Math.random() * array.length);
}
var randomFoods = createRandomArray(5);
for (var i = 0; i < randomFoods.length; i++) {
document.getElementById('food-form').innerHTML += '<input type="radio" name="food" value="' + randomFoods[i] + '"> ' + randomFoods[i] + '<br>';
}
function print() {
var t = document.querySelector('input[name=food]:checked');
if (t == null)
console.log('No value selected');
else
console.log(t.value);
}
<form action="" id="food-form">
</form>
<input type="submit" id="btn" value="Submit" onClick="print()">

First function calls on html button onclick, but not any others

I've just begun learning javascript, and I'm running into an issue where only one of my 3 currently coded buttons will either recognize a click, or run the function associated when I click it. This first example of code works wonderfully;
The HTML
<div id="commonchecks">
<h3>Common Checks:</h3>
<p>Type of Check:</p>
<select id="CheckType">
<option value="Strength">Strength</option>
<option value="Stamina">Stamina</option>
<option value="Agility">Agility</option>
<option value="Intelligence">Intelligence</option>
<option value="Charisma">Charisma</option>
<option value="Perception">Perception</option>
</select>
<p>Complexity:</p>
<select id="Complexity">
<option value="Simple">Simple</option>
<option value="Complex">Complex</option>
</select>
<p>Circumstantial Factors (+/-):</p>
<input type="number" id="bxCircumstantialFactors" value="-2">
<h3 class="details">Check Details:</h3>
<p id="success" class="details">It was a XXXXXXX!</p>
<p id="rolltotal" class="details">You rolled a(n) XX.</p>
<p id="rollstandards" class="details">You needed a(n) XX or higher.</p>
<p id="experience" class="details">Experience Payout: 00 exp!</p>
<p id="duplicate">DUPLICATE!</p>
<button onclick="CheckRoll()" class="button" id="RollCheckButton">Roll</button>
</div>
And the javascript
function CheckRoll() {
//Loading Variables Up From User Input
numStrength = Number(document.getElementById("bxStrength").value);
numStamina = Number(document.getElementById("bxStamina").value);
numAgility = Number(document.getElementById("bxAgility").value);
numIntelligence = Number(document.getElementById("bxIntelligence").value);
numCharisma = Number(document.getElementById("bxCharisma").value);
numPerception = Number(document.getElementById("bxPerception").value);
numCircumstantialFactors = Number(document.getElementById("bxCircumstantialFactors").value);
//Making the Roll
numRoll = Math.floor(Math.random() * 20 + 1);
if (document.getElementById("duplicate").style.visibility === "visible"){
document.getElementById("duplicate").style.visibility = "hidden";
}
//Checking to see if the roll was a duplicate
if (numRoll === prevRoll) {
document.getElementById("duplicate").style.visibility = "visible";
}
//Checking the complexity of the check
switch (document.getElementById("Complexity").value){
case "Simple":
numBaseAddition = 10;
numStatModifier = 2;
break;
case "Complex":
numBaseAddition = 0;
numStatModifier = 1;
break;
}
//Checking the stat associated and marking it as the calculated stat
switch (document.getElementById("CheckType").value) {
case "Strength":
numRelevantStatValue = numStrength;
break;
case "Stamina":
numRelevantStatValue = numStamina;
break;
case "Agility":
numRelevantStatValue = numAgility;
break;
case "Intelligence":
numRelevantStatValue = numIntelligence;
break;
case "Charisma":
numRelevantStatValue = numCharisma;
break;
case "Perception":
numRelevantStatValue = numPerception;
break;
}
//Determining how much value of a stat effects your chances of success
numStatAddition = numRelevantStatValue / numStatModifier;
//Determining your factor of success
numSuccessFactor = numBaseAddition + numStatAddition + numCircumstantialFactors;
//If success factor is a 20 or higher, set it to 19 since one can always roll a 1
if (numSuccessFactor >= 20){
numSuccessFactor = 19;
}
//Calculating the number you need to beat
numFailureFactor = 20 - numSuccessFactor;
//If failure factor is a 20 or higher, set it to 19 since one can always roll a 20
if (numFailureFactor >= 20) {
numFailureFactor = 19;
}
//Calculating amount of experience possible to be earned
numExperience = numFailureFactor * 5;
//Reporting on the successfulness or not
if (numRoll >= numFailureFactor + 1){
document.getElementById("success").innerHTML = "It was a SUCCESS!";
}
if (numRoll === 20){
document.getElementById("success").innerHTML = "It was a CRITICAL SUCCESS!";
}
if (numRoll < numFailureFactor + 1){
document.getElementById("success").innerHTML = "It was a FAILURE!";
numExperience = 0;
}
if (numRoll === 1){
document.getElementById("success").innerHTML = "It was a CRITICAL FAILURE!";
numExperience = 0;
}
//Reporting the dice roll
document.getElementById("rolltotal").innerHTML = "You rolled a(n) " + numRoll + ".";
//Reporting the standards
document.getElementById("rollstandards").innerHTML = "You needed a(n) " + (numFailureFactor + 1) + " or higher.";
//Reporting experience gain
document.getElementById("experience").innerHTML = "Experience Payout: " + numExperience + " exp!";
//Saving last roll
prevRoll = numRoll;
However, on a much simpler function, it won't work for whatever reason. I've tried putting the javascript into firefox's debugger, and it didn't reveal any syntax mistakes. Here's the section that won't work.
The HTML
<p class="blocksection">Block Type:</p>
<select id="blocktype">
<option value="Unarmed">Unarmed</option>
<option value="Armed">Armed</option>
</select>
<p class="blocksection" id="blockreporter">Your Block total is a(n) XX!</p>
<p class="blocksection" id="blockduplicate">DUPLICATE!</p>
<button onclick="BlockRoll()" class="button" id="blockbutton">Block!</button>
And the javascript
function BlockRoll() {
numStamina = Number(document.getElementById("bxStamina").value);
if (document.getElementById("blocktype").value === "Unarmed") {
document.getElementById("blockreporter").InnerHTML = "Your Block total is a(n) " + Math.floor(Math.random() * 6 + 1) + "!";
}
else {
document.getElementById("blockreporter").InnerHTML = "Your Block total is a(n) " + (Math.floor(Math.random() * 6 + 1) + (numStamina/2)) + "!";
}
}
I'm not used to this language, but I know c# well enough and they appear relatively similar. Is there a really simple mistake that I'm making somewhere?
Thanks
You're calling element.InnerHTML in your second example which is incorrect, as the correct value is innerHTML (note the lowercase i.)
If you hit F12 (in most browsers) the developer console will come up and show you common errors like these.

Cannot read property 'fontWeight' of undefined

I am writing a simple quiz application.
It was working fine until I try to edit the font for the selected radio buttonvar labelStyle = userpick.style.fontWeight;
Anyone able to spot the problem??
Also, if possibe, suggestion to improve the code?
I have made some new changes to the checkAnswer function
// define all the elements
var content = $("content");
var questionContainer = $("question");
var choicesContainer = $("choices");
var scoreContainer = $("score");
var submitBtn = $("submit");
//init variables
var currentQuestion = 0;
var score = 0;
var askingQuestion = true;
//shortcut for document.getElementById
function $(id){
return document.getElementById(id);
}
//askQuestion Function to load question into id = question
function askQuestion (){
var choices = quiz[currentQuestion].choices;
var choicesHtml = "";
//loop through chocies and create a radio button
for (var i = 0; i < choices.length; i++){
choicesHtml += "<input type = 'radio' name = 'quiz" + currentQuestion +
"' id = 'choice" + (i + 1) +
"' value ='" + choices[i] + "'>" +
"<label for ='choice" + (i + 1) + "'>" + choices[i] + "</label></br>";
}
//load the Question
questionContainer.textContent = "Q" + (currentQuestion + 1) + ". " + quiz[currentQuestion].question;
//load the choices
choicesContainer.innerHTML = choicesHtml;
//setup for the first time
if(currentQuestion === 0){
scoreContainer.textContent = "Score : 0 right answer out of " +
quiz.length + " possible.";
submitBtn.textContent = "Submit Answer";
}
}
//checkAnswer function to match user input with quiz.correctAnswer
function checkAnswer(){
//
if (askingQuestion){
submitBtn.textContent = "Next Question";
askingQuestion = false;
//determine if radio button is clicked
var userpick;
var correctIndex;
var radios = document.getElementsByName("quiz" + currentQuestion);
for (var i = 0 ; i < radios.length; i++){
if(radios[i].checked){
//if radio button is checked
userpick = radios[i].value;
}
if(radios[i].value == quiz[currentQuestion].correct){
correctIndex = i;
}
}
//if they got it right or wrong
var labelStyle = document.getElementsByTagName('label')[correctIndex].style;
labelStyle.fontWeight = "bold";
if (userpick == quiz[currentQuestion].correctAnswer) {
score++;
labelStyle.color = "green";
}else{
labelStyle.color = "red";
}
scoreContainer.textContent = "Score: "+ score + "right answers out of "+
quiz.length + " possible.";
}
function showFinalResults(){
content.innerHtml = "<h2> You've completed the quiz</h2" +
"<h2> Below are your results </h2>" +
"<h2>" + score + " out of " + quiz.length +
"questions, " + Math.round(score/quiz.length * 100) + "% </h2>";
}
}
window.addEventListener("load", askQuestion, false);
submitBtn.addEventListener("click", checkAnswer, false);
var quiz = [{"question": "Question 1: Grand Central Terminal, Park Avenue, New York is the world's",
"choices": ["A: largest railway station",
"B: highest railway station",
"C: longest railway station",
"D: None of the above"],
"correctAnswer": 0
},
{"question": "Question 2: Entomology is the science that studies",
"choices": ["A: Behavior of human beings",
"B: Insects",
"C: The origin and history of technical and scientific terms",
"D: The formation of rocks"],
"correctAnswer": 1
},
{"question": "Question 3: Friction can be reduced by changing from",
"choices": ["A: sliding to rolling",
"B: rolling to sliding",
"C: potential energy to kinetic energy",
"D: dynamic to static"],
"correctAnswer": 0
},
{"question": "Question 4: For seeing objects at the surface of water from a submarine under water, the instrument used is",
"choices": ["A: kaleidoscope",
"B: spectroscope",
"C: periscope",
"D: telescope"],
"correctAnswer": 2
},
{"question": "Question 5: Galileo was an Italian astronomer who",
"choices": ["A: developed the telescope",
"B: discovered four satellites of Jupiter",
"C: discovered that the movement of pendulum produces a regular time measurement",
"D: All of the above"],
"correctAnswer": 3
},
{"question": "Question 6: Habeas Corpus Act 1679",
"choices": ["A: states that no one was to be imprisoned without a writ or warrant stating the charge against him",
"B: provided facilities to a prisoner to obtain either speedy trial or release in bail",
"C: safeguarded the personal liberties of the people against arbitrary imprisonment by the king's orders",
"D: All of the above"],
"correctAnswer": 3
},
{"question": "Question 7: For galvanizing iron which of the following metals is used?",
"choices": ["A: Aluminium",
"B: Lead",
"C: Zinc",
"D: Copper"],
"correctAnswer": 2
}];
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head lang = "en">
<title> Quiz </title>
</head>
<body>
<div class = "page-header">
<h1>Simple Javascript Quiz</h1>
</div>
<div id = "content">
<h3 id = "question"> </h3>
<div id = "choices"> </div>
<button id = "submit">Submit</button>
<p id ="score"></p>
</div>
<script src = 'quiz2.js'></script>
</body>
</html>
userpick.style.fontWeight;
Cannot read property 'fontWeight' of undefined
That means that userpick.style is undefined.
Relevant code:
var userpick;
for (var i = 0; i < radios.length; i++)
if(radios[i].checked){
userpick = radios[i].value;
If no radio was checked, userpick.style.fontWeight would throw, but the error would be
Cannot read property 'style' of undefined
That means that there is some checked radio, so userpick is not undefined.
But userpick.style is undefined. And thats because the value of a radio is a string, and by default strings have no style property.
Probably, you want userpick to be the checked radio, not its value
var userpick;
for (var i = 0; i < radios.length && !userpick; ++i)
if(radios[i].checked)
userpick = radios[i];
However, let me introduce querySelector and the :checked pseudo-class:
var userpick = document.querySelector(".quiz" + currentQuestion + ":checked");
In this piece of your code:
var radios = document.getElementsByName("quiz" + currentQuestion);
for (var i = 0 ; i < radios.length; i++){
if(radios[i].checked){
//if radio button is checked
userpick = radios[i].value;
}
}
//if they got it right or wrong
var labelStyle = userpick.style.fontWeight;
You put the VALUE of the selected radio button in the userpick variable. The style object is only available on a DOM element. Which is not the value of said element.
If you do: userpick = radios[i]; instead, it will work.
There are a few problems.
var labelStyle = usepick.style.fontWeight;
fontWeight is a string type.
However, later, you try labelStyle.color = "green"
The color property doesn't exist in a string.
However, worse than that userpick is a string itself!
This is because userpick = radios[i].value - value is a string type.
Most Importantly - you are trying to set fontWeight or color of a radio button - there is no text node in a radio button, so it won't make any visible difference - you need to select the label associated with that button and set THAT font weight and color.

how to get selected text surrounding context in javascript in different paragraph?

hi I have a few problems:
What might I get the word around the word selected, if the word before and after the selected word given limits only 20 words that surround the selected word?
how to get the correct position if the word in a paragraph have the same word, for example I have a sentence like this: foo laa foo doo then I choose the word "foo" whose position is in between the words laa and doo?
how to get word from a different paragraph?
for example:
p1 : I like the red shirt
p2: my mother did not like the red shirt
the word I selected is "mother", and I have to take 10 words around the word "mother" that is "I like the red dress" and "I do not like the red shirt."
notes:
question No. 2 is able to use the nextSibling and previousSibling?
this is my code i try :
<html>
<head>
<script type="text/javascript">
function getElements(){
var x = document.getElementsByTagName("body");
x = x[0].innerHTML;
x = x.replace(/&(lt|gt);/g, function (strMatch, p1){
return (p1 == "lt")? "<" : ">";});
var str = x.replace(/<\/?[^>]+(>|$)/g, "");
var emailPattern = /[_a-zA-Z0-9\.]+#[\.a-zA-Z0-9]+\.[a-zA-Z]+/gi;
var urlPattern = /[a-z]+:\/\/[^\s]+/gi;
var numberOrSymbolPattern = /[0-9\.,!##\$%\^\&*\(\)`~_\-=\+|\\{}\[\]\s:;<>\?\/]+/gi;
//////alert(str);
var str = str.replace(emailPattern , " ");
var str = str.replace(urlPattern , " ");
var str = str.replace(numberOrSymbolPattern , " ");
//////alert(str);
var str = str.replace(/[\n\f\r\t]/g, " ");
var hilangtandabaca = str.replace(/[.!:;'",?]/g," ");
var kataptg = hilangtandabaca;
//alert(kataptg);
var kata = new Array();
kata[0] = " is ";
kata[1] = " the ";
kata[3] = " of ";
kata[4] = " a ";
kata[5] = " or ";
kata[6] = " for ";
kata[7] = " from ";
kata[8] = " in ";
kata[9] = " this ";
kata[10] = " and ";
kata[11] = " on ";
kata[12] = " with ";
kata[13] = " my ";
for(var i=0,regex; i<kata.length; i++){
var regex = new RegExp(kata[i],"gi");
kataptg = kataptg.replace(regex," ");
}
var select = getSelected()+ "";
alert(select);
var index = kataptg.indexOf(select);
//alert("indeks select text:" + index);
if (index >= 0) {
var strBefore = "";
var strAfter = "";
//var strOri ="";
//if (index = -1)
//strOri = kataptg.substr(index);
//alert(strOri);
if (index > 0)
strBefore = kataptg.substr(0, index);
//alert(strBefore);
if (index < kataptg.length - 1)
strAfter = kataptg.substr(index + select.length, kataptg.length - (index + select.length));
//alert(strAfter);
alert("Before: " + strBefore + "\nAfter: " + strAfter);
}
}
function getSelected() {
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
} else if (document.selection) {
userSelection = document.selection.createRange();
}
return userSelection;
}
</script>
</head>
<body>
<h2>About</h2>
<p> my email : a#a.a
<p> my url http://id.wikipedia.org/wiki/URL
<p> my telepon number = 081330782
<p>okey In agriculture, the harvest is the process of gathering mature crops from the fields. Reaping is the cutting of grain or pulse for harvest, typically using a scythe, sickle, or reaper.[1] The harvest marks the end of the growing season, or the growing cycle for a particular crop, and this is the focus of seasonal celebrations of on many religions. On smaller farms with minimal mechanization, harvesting is the most labor-intensive activity of the growing season great yeah. !:;'",?</p>
<p>
<input type="button" onclick="getElements()" value="ambil select text" />
</p>
</body>
</html>
This is a perfect example of JavaScript's innerHTML and split() methods. You can loop through the content of all of the p elements. Here's an example of searching in the first paragraph:
contentArray = document.getElementByTagName('p')[0].innerHTML.split(' ')
split(' ') splits the content of the element into an array, separating by the spaces. innerHTML is self explanatory.
Now, to find your words. indexOf() is your friend in this case:
foodex = contentArray.indexOf('foo');
alert('The first occurrence of the string \'foo\' in the text is at word number ' + foodex);
Finally, to get surrounding words, just play with the array (this won't work if the occurrence of the string is close to the start or end of the paragraph, namely less than 10 words away:
alert('I am the 10th word after \'foo\'' + contentArray[foodex + 10 - 1]);
Good luck (no guarantees this code works out of the box)!

Categories