We have a fairly simple function called alert which basically creates an alert card (HTML element) anytime it is triggered. For reference we are using Eel to pass variables from Python and run this in a chrome wrapper.
<script type="text/javascript">
eel.expose(alert);
function alert(serial, time_key, card_color, screen_msg, ping) {
//clone card_template for each new alert
var clone = $("#card_template").clone();
clone.attr("id", serial);
clone.find("#message-card").attr("id", "message-card-" + serial + "-" + time_key);
clone.find("#python-data").attr("id", "python-data-" + serial + "-" + time_key);
//append clone on the end
$("#message-zone").prepend(clone);
document.getElementById("message-card-" + serial + "-" + time_key).classList.remove('bg-info');
document.getElementById("message-card-" + serial + "-" + time_key).className += card_color;
document.getElementById("python-data-" + serial + "-" + time_key).innerHTML = screen_msg;
var button_template = '<button type="button" class="btn btn-sm btn-danger">Clear</button>';
var selector_id = 'python-data-' + serial + '-' + time_key;
// $('#python-data-'+ serial + '-' + time_key).append(button_template);
$('#'+ selector_id).append(button_template);
$('#python-data').append(button_template);
if (ping === true)
document.getElementById('alert').play();
}
</script>
It clones and alters this element based on the type of alert that is received.
<div class="row justify-content-center" id="card_template">
<div class="col-md-8">
<div class="card bg-info" id="message-card">
<div class='card-body' id="python-data">
No messages
</div>
</div>
</div>
</div>
So this is where we are losing it. We want to append a HTML block to the cards after they are cloned and given unique ids. We have created a variable button_template that contains that code block. We can insert this code block easily into an element with a hardcoded id.
For example:
$('#python-data').append(button_template);
Will append the code block to the #python-data div in the original (clone source) card.
But we can't seem to get it to work when our selector is assembled from variables (necessary to address the cloned alert cards with unique ids).
Neither:
var selector_id = 'python-data-' + serial + '-' + time_key;
$('#'+ selector_id).append(button_template);
or
$('#'+ 'python-data-' + serial + '-' + time_key).append(button_template);
Works on the newly cloned cards.
TLDR Everything else on this function works. It clones our starting element, gives it, and its children, a unique id (assembled from variable), removes a class, adds a class and writes a message to the innermost div. This all works. All we need help with is appending a HTML block to a div with a unique, variable-based id.
This is the jsfiddle link (https://jsfiddle.net/abhishekraj007/w3m3r8oL/12/) I created to understand your code. Here I hardcoded unique ids while passing to function and its working. Something like this:
aalert("serial1", "a", "blue", "message", true)
aalert("serial2", "b", "blue", "message", true)
I've changed function name because alert is reserved Javascript function. Please check and let me know if this not what you want.
I have created a codepen from your code and its working fine there. The issue is must be somewhere else in your code.
My code.
JS
var serial = "123";
var time_key = "67868678";
var card_color = "bg-warning";
var screen_msg = "This is new message";
var clone = $("#card_template").clone();
clone.attr("id", serial);
clone.find("#message-card").attr("id", "message-card-" + serial + "-" + time_key);
clone.find("#python-data").attr("id", "python-data-" + serial + "-" + time_key);
//append clone on the end
$("#message-zone").prepend(clone);
document.getElementById("message-card-" + serial + "-" + time_key).classList.remove('bg-info');
document.getElementById("message-card-" + serial + "-" + time_key).className += " "+card_color;
document.getElementById("python-data-" + serial + "-" + time_key).innerHTML = screen_msg;
var button_template = '<button type="button" class="btn btn-sm btn-danger">Clear</button>';
var selector_id = 'python-data-' + serial + '-' + time_key;
$('#'+ selector_id).append(button_template);
$('#python-data').append(button_template);
HTML
<div class="row justify-content-center" id="card_template">
<div class="col-md-8">
<div class="card bg-info" id="message-card">
<div class='card-body' id="python-data">
No messages
</div>
</div>
</div>
</div>
<div id="message-zone"></div>
Here is a codepen.
I think this issue is related to duplicate IDs. Can you please check the unique IDs you are generating are really unique?
I've written a simple mad lib programme in JavaScript. All of its working except one thing. My name value is showing undefined. The code is below. Please help me to find out the error.
And here is codepen link.
HTML:
Name: <input type="text" id="name">
Favourite Color: <input type="text" name="color" id="color">
Fovourite Place: <input type="text" name="place" id="place">
Number: <input type="number" name="number" id="number">
<button id="launch">Launch</button>
<div id="story"></div>
Js:
var name = document.querySelector("#name");
var color = document.querySelector("#color");
var place = document.querySelector("#place");
var number = document.querySelector("#number");
var story = document.querySelector("#story")
var launch = document.querySelector("#launch");
launch.addEventListener("click", writeStory, false);
function writeStory(){
var launchedStory = "";
launchedStory += "<p>Welcome, " + name.value + ". ";
launchedStory += "Only silly people choose " + color.value + " as their favorite color.</p>";
launchedStory += "<p>Is " + place.value + " your current place or your birth place.</p>";
launchedStory += "<p>By the way, " + number.value + " is your serial number.</p>";
story.innerHTML = launchedStory;
}
You need to change the variable name from name to something else because the interpreter is resolving it as window.name instead.
Write your code inside script tag in windows event onload function. The global variable name is conflicting with window object's name property. You can also change the name of global variable from name to something else.
Sol 1.
var nameElement = document.querySelector("#name");
Then you can read its value using nameElement.value
But it is good to not pollute the global namespace. So write your code in function scope.
Sol 2.
<script type="text/javascript">
window.onload = function () {
// your code here
}
</script>
Here is fiddle https://jsfiddle.net/mrk_m/L1an24ut/1/
It's been answered above but in a more complex way. Simply put, "name" is a JavaScript keyword and shouldn't be used as a variable. I changed the id of "name" to "nombre", and it worked just fine.
https://codepen.io/SuperSchooler/pen/qeVqOj
HTML:
Name: <input type="text" id="nombre">
Favourite Color: <input type="text" name="color" id="color">
Favourite Place: <input type="text" name="place" id="place">
Number: <input type="number" name="number" id="number">
<button id="launch">Launch</button>
<div id="story"></div>
JS:
var name = document.querySelector("#nombre");
var color = document.querySelector("#color");
var place = document.querySelector("#place");
var number = document.querySelector("#number");
var story = document.querySelector("#story")
var launch = document.querySelector("#launch");
launch.addEventListener("click", writeStory, false);
function writeStory(){
var launchedStory = "";
launchedStory += "<p>Welcome, " + nombre.value + ". ";
launchedStory += "Only silly people choose " + color.value + " as their favorite color.</p>";
launchedStory += "<p>Is " + place.value + " your current place or your birth place.</p>";
launchedStory += "<p>By the way, " + number.value + " is your serial number.</p>";
story.innerHTML = launchedStory;
}
If you are doing madlibs, then do:
puts "give me a transportation"
transportation = gets.chomp
Then,
puts "then we got in the {transportation} and went to Wendy's"
I have a textbox for users to enter a new email address. I have a button that calls a script. In the script I need to access several different elements of the page. The first couple of elements, that were sent as parameters to the page (via PHP) work fine, but I do not get the right result when I try to get the value of the text box.
This is my HTML:
<p>Please enter the new email</p>
<input type="email" id="newemail" value="enter new email here">
and this is my JS:
var userid=$('#userId').val();
var oldEmail=$('#useremail').val();
var newEmail=$('#newemail').val();
//I have also tried with var newEmail=document.getElementById("newemail").value
//with no difference in the result
alert(userid + " " + oldEmail + " " + newemail);
The alert prints out :
5 Sammy [object HTMLInputElement]
I note that it is printing neither the old value of the text box nor the new value which the user entered. How to I get it to get that value?
Javascript is case sensitive. newemail should be newEmail.
When referencing newemail you are accessing window.newemail which will by default return the DOM element with ID newemail. Calling .toString() on that DOM element produces [object HTMLInputElement].
Change the alert to:
alert(userid + " " + oldEmail + " " + newEmail);
The variable is newEmail, but in alert you are using newemail, they are case sensitive.
Then how newemail is working, because since it is the id of an element the property will be added as a window elements property
replace
alert(userid + " " + oldEmail + " " + newemail);
by
alert(userid + " " + oldEmail + " " + newEmail);
Is it possible that there is a typo?
alert(userid + " " + oldEmail + " " + newemail);
doesnt fit the variable declarations:
var newEmail=$('#newemail').val();
I hope this makes sense. I have an onclick and I am trying to write this data for each div with this.
jQuery('.circle_counter_div').each(function() {
var tagtext = '[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]';
})
I am cloning items but I can only write the data for one of them. How do I write data for each cloned item?
So with the above example I want tagtext to equal
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
Full Code
HTML
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<input type="submit" class="sc_options circle_counter_div" id="insert" name="insert" value="<?php _e("Insert", 'themedelta'); ?>" onClick="insertcirclecountershortcode();" style="display:none"/>
Script
// Insert the column shortcode
function insertcirclecountershortcode() {
var tagtext;
var start;
var last;
var start = '[circlecounters]';
var last = '[/circlecounters]';
jQuery('.circle_counter_div').each(function() {
var tagtext = '[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]';
})
var finish = start + tagtext + last;
if (window.tinyMCE) {
window.tinyMCE.execInstanceCommand(window.tinyMCE.activeEditor.id, 'mceInsertContent', false, finish);
//Peforms a clean up of the current editor HTML.t
//tinyMCEPopup.editor.execCommand('mceCleanup');
//Repaints the editor. Sometimes the browser has graphic glitches.
tinyMCEPopup.editor.execCommand('mceRepaint');
tinyMCEPopup.close();
}
return;
}
Extended Answer: After some more information was provided perhaps you're just missing the index and value properties on the loop. Its hard to tell, since little sample code is provided.
$('.test').each(function(i,v) {
var tagtext = $(v).html();
console.log(tagtext);
})
http://jsfiddle.net/4xKvh/
Original Answer:
Use use classes instead of an Id. Id's are only suposed to be used once on a page.
Since there should only be one occurance jQuery is filtering the result down to 1, even though the markup may have multiple elements with that Id on the page. This is to make use of the built-in browser function getElementById().
For proof checkout this jsFiddle
Using the class attribute is more appropriate for what you're trying to do.
jQuery('.clone_this').each(function() {
var tagtext = '[something][/something]';
})
And the markup:
<div class="clone_this"></div>
This will allow jQuery to return an array of elements like you're looking for
This is what I needed... Finally got it working.
tagtext = ' ';
jQuery('#circle_counter_div .circlecounter').each(function() {
tagtext += '[circlecounter rel="' + jQuery('.circle_size').val() + '" datathickness="' + jQuery('.circle_thickness').val() + '" datafgcolor="' + jQuery('.circle_color').val() + '" text="' + jQuery('.circle_text').val() + '" fontawesome="' + jQuery('.font_awesome_icon').val() + '" fontsize="' + jQuery('.circle_font_size').val() + '"][/circlecounter]';
});
var start = '[circlecounters]';
var last = '[/circlecounters]';
var finish = start + tagtext + last;
I am trying to create a button that upon clicking, fills an input box located right next to it with 3 random words and 2 preset words.
I have the 5 words with JQuery & Javascript going into <p> tags as of now, but I cannot figure out for my life how to get them into the input box.
Here's what I have so far for the JavaScript:
jsfiddle link
It's forcing me to put some of the code, so here is the short amount of HTML I have for it.
<h1>Shakespearean Insult Generator</h1>
<div>
<p id=word4></p>
<p id=word1></p>
<p id="word2"></p>
<p id="word3"></p>
<p id=word5></p>
</div>
<input type="text" name="message" size="50" value="Thou">
<button id="wordGen">Click Me!</button>
It sounds like your only issue is with how to set the value of a text input. Use jQuery's val method to set the value of the text input to the complete sentence that you have constructed. See:
http://api.jquery.com/val/
You should give the text input an id attribute (not necessary, as you could select by name), eg.
<input type="text" name="message" size="50" value="Thou" id="finalMessage">
and then something like this to select and set its value:
// construct the sentence
var finalMessage = 'Thou ' + words1[getWord1()] + ' ' + words2[getWord2()] + ' ' + words3[getWord3()];
// set the value of the text input to the sentence
$("#finalMessage").val(finalMessage);
As others have suggested you could also improve your method of selecting a random word to make it more reusable.
Try this :
$('#wordGen').click(function() {
$('#word1').html("");
$('#word2').html("");
$('#word3').html("");
$('#word1').append('<input value="' + words1[getWord1()] + '"></input>');
$('#word2').append('<input value="' + words2[getWord2()] + '"></input>');
$('#word3').append('<input value="' + words3[getWord3()] + '"></input>');
});
Fiddle : https://jsfiddle.net/DinoMyte/fy1asfws/24/
If you have your three words and you need to put them in the <input>, then you need to use $("#message").val() to set the text for the input. Also, for this to work, you need to add id="message" to the <input> tag so that it becomes <input type="text" id="message" name="message" size="50" value="Thou">. For instance, your code might look like this:
val word1 = words1[getWord1()];
val word2 = words1[getWord2()];
val word3 = words1[getWord3()];
$('#word1').text(word1);
$('#word2').text(word2);
$('#word3').text(word3);
$("#message").val(word1 + " " + word2 + " " + word3);
Essentially, as I can see from the jsfiddle link, your question boils down to how to set the value property of an input field.
As you're using jQuery, this can be done by using the val() method.
In action for your generator:
$('input[name=message]').val(insultFunctionWord1() + insultFunctionWord2());
The javascript alternative is just as concise as the solutions written in jQuery (and, arguably, could be abbreviated further):
function getWord(i) {
var randomNumber = Math.floor(Math.random() * words[(i-1)].length);
return words[(i-1)][randomNumber];
}
document.querySelector('#wordGen').onclick = function() {
var insult = getWord(1) + ' ' + getWord(2) + ' ' + getWord(3);
document.querySelector('input').value = insult;
}
Here is the full solution in plain vanilla javascript:
var words = [
['artless',
'bawdy',
'beslubbering',
'bootless',
'churlish',
'cockered',
'clouted',
'craven',
'currish',
'dankish',
'dissembling',
'droning',
'errant',
'fawning',
'fobbing',
'froward',
'frothy',
'gleeking',
'goatish',
'gorbellied',
'impertinent',
'infectious',
'jarring',
'loggerheaded',
'lumpish',
'mammering',
'mangled',
'mewling',
'paunchy',
'pribbling',
'puking',
'puny',
'qualling',
'rank',
'reeky',
'roguish',
'ruttish',
'saucy',
'spleeny',
'spongy',
'surly',
'tottering',
'unmuzzled',
'vain',
'venomed',
'villainous',
'warped',
'wayward',
'weedy',
'yeasty',
],
['base-court',
'bat-fowling',
'beef-witted',
'beetle-headed',
'boil-brained',
'clapper-clawed',
'clay-brained',
'common-kissing',
'crook-pated',
'dismal-dreaming',
'dizzy-eyed',
'doghearted',
'dread-bolted',
'earth-vexing',
'elf-skinned',
'fat-kidneyed',
'fen-sucked',
'flap-mouthed',
'fly-bitten',
'folly-fallen',
'fool-born',
'full-gorged',
'guts-griping',
'half-faced',
'hasty-witted',
'hedge-born',
'hell-hated',
'idle-headed',
'ill-breeding',
'ill-nurtured',
'knotty-pated',
'milk-livered',
'motley-minded',
'onion-eyed',
'plume-plucked',
'pottle-deep',
'pox-marked',
'reeling-ripe',
'rough-hewn',
'rude-growing',
'rump-fed',
'shard-borne',
'sheep-biting',
'spur-galled',
'swag-bellied',
'tardy-gaited',
'tickle-brained',
'toad-spotted',
'unchin-snouted',
'weather-bitten',
],
['apple-john',
'baggage',
'barnacle',
'bladder',
'boar-pig',
'bugbear',
'bum-bailey',
'canker-blossom',
'clack-dish',
'clotpole',
'coxcomb',
'codpiece',
'death-token',
'dewberry',
'flap-dragon',
'flax-wench',
'flirt-gill',
'foot-licker',
'fustilarian',
'giglet',
'gudgeon',
'haggard',
'harpy',
'hedge-pig',
'horn-beast',
'hugger-mugger',
'joithead',
'lewdster',
'lout',
'maggot-pie',
'malt-worm',
'mammet',
'measle',
'minnow',
'miscreant',
'moldwarp',
'mumble-news',
'nut-hook',
'pigeon-egg',
'pignut',
'puttock',
'pumpion',
'ratsbane',
'scut',
'skainsmate',
'strumpet',
'varlot',
'vassal',
'whey-face',
'wagtail',
]
];
function getWord(i) {
var randomNumber = Math.floor(Math.random() * words[(i-1)].length);
return words[(i-1)][randomNumber];
}
document.querySelector('#wordGen').onclick = function() {
var insult = getWord(1) + ' ' + getWord(2) + ' ' + getWord(3);
document.querySelector('input').value = insult;
}
button {
background-image: url( 'https://media.giphy.com/media/URZcG7uLd9h4s/giphy.gif' );
background-size: 100px 130px;
height: 250;
width: 250;
//background-size: auto;
font: 15px Verdana, sans-serif;
}
h1 {
font: 35px Arial, sans-serif;
}
<h1>Shakespearean Insult Generator</h1>
<input type="text" size="30" />
<button id="wordGen">Click Me!</button>