Attempting to make a phrase generator - javascript

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>

Related

Number of items does not appear in the list of arrays

Number of items does not appear in the list of arrays when sending to whatsapp. Only the item name and value. How could I solve it? Can someone help me?
When I click to send to whatsapp, the correct name and value is sent, but the quantity of the item is not informed. What am I doing wrong?
CODE ONLINE:
https://codepen.io/cinthia-danielle/pen/PoNQBdR
<script>
function displayCart() {
var cartArray = shoppingCart.listCart();
var output = "";
for(var i in cartArray) {
output += `<tr>
<td style="font-size:12px;"><strong>•</strong> ${cartArray[i].name}</td>
<td><div class='input-group'><button class='minus-item input-group-addon btn btn-primary menosItemCB' data-name='${cartArray[i].name}'>-</button>
<input type='button' style="margin:2px; font-size:12px;" class='item-count form-control numberItemCB' data-name='${cartArray[i].name}' value='${cartArray[i].count}'><button style="margin-left: 4px;" class='plus-item btn btn-primary input-group-addon maisItemCB' data-name='${cartArray[i].name}'>+</button></div></td>
=
<td style="font-size:12px;"> $ ${cartArray[i].total}<button class='delete-item btn btn-danger deleteItemCB' data-name='${cartArray[i].name}''>delete</button></td>
</tr><br>`;
}
$('.send_form').on("click",function(){
var input_blanter = document.getElementById('wa_name');
/* Whatsapp Settings */
var walink = 'https://web.whatsapp.com/send',
phone = 'xxxxxxxxxxxx',
walink2 = 'Cart Items';
/* Smartphone Support */
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
var walink = 'whatsapp://send';
}
if("" != input_blanter.value){
/* Call Input Form */
var totalC = total.toFixed(2);
/* Final Whatsapp URL */
var blanter_whatsapp = walink + '?phone=' + phone + '&text=' + walink2 + '%0A%0A' +
'Name : ' + input_name1 + '%0A%0A' + 'Cart: ' + totalC + '%0A%0A' + itemsCart ;
/* Whatsapp Window Open */
window.open(blanter_whatsapp,'_blank');
}
});
}
displayCart();
</script>
HTML:
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<table class="show-cart table"></table>
<form class="whatsapp-form">
<input class="validate" id="wa_name" name="name" required="" type="text" value=''/>
<label>Your Name</label>
<a class="send_form" href="javascript:void" type="submit" title="Send to Whatsapp">Send to Whatsapp</a>
</form>
</body>
EDIT
So far I tried to make the script work, but I couldn't. The list does not come with the number of items. I am a beginner and am unable to find an answer.
As commented before the issue is that when you use .text() to get your info, is not getting the amount of products because you are using an input.
In this case innerText will not contain any text, because the info you want to get is in the input's value attribute.
The best way to go about this would be to build your itemsCart string from your variables in your javascript code and not from the html generated.
However if you want to do it like that, you should iterate over each td in a tr. And use the value attribute to get your amount of products, like so:
itemsCart = $(".show-cart > tbody > tr").toArray().map(productItem => {
let desc = $(productItem).children('td:nth-child(1)').text() + ',';
desc += ' Amount: ' + $(productItem).find('td > div > input').val() + ',';
desc += ' Price: ' + $(productItem).children('td:nth-child(3)').text();
return desc;
}).join('\n')
Then add to your URL with :
encodeURI(itemsCart)
that will yield:
%E2%80%A2%20Product%20three,%20Amount:%203,%20Price:%20$%2090.00%20%0A%E2%80%A2%20Product%20two,%20Amount:%201,%20Price:%20$%2020.00%20
which decoded is:
• Product three, Amount: 3, Price: $ 90.00
• Product two, Amount: 1, Price: $ 20.00
I would also recommend not using %0A, just build your string as if you were to output that to console and then do encodeURI(text) to add it to your URL.
It will make your code much more readable.
PD:Also try to indent properly your code to make it more readable.

Alternative to TextArea with more control over text?

I am working on a chat project, and have mostly finished everything that I needed. My chat box is a textarea and for the most part it works, until I wanted to implement changing the color of certain words in the chatbox by using regex.
But looking at how I have this set up:
function writeMessageToChatBox(message, from, serverMessage=false, direct=false){
let chat_box = $('#chatbox');
let val = chat_box.val();
if(!serverMessage){
if(direct){
console.log(replay);
if(replay){
chat_box.val(val + '[Whisper to: ' + tempRecepient + ' ] ' + from + ": " + message + "\n" );
replay = false;
tempRecepient = undefined
}
else{
chat_box.val(val + '[Whisper from: ' + from + ' ] ' + from + ": " + message + "\n" );
}
}
else{
chat_box.val(val + from + ": " + message + "\n");
}
}
else{
chat_box.val(val + message + "\n");
}
chat_box.scrollTop(document.getElementById("chatbox").scrollHeight);
I've come to realize that textareas hold text within them in their value, but the text are not elements within the textarea so I cannot pick and choose which text gets style. From some research I saw that what I'm trying to do is not possible with a textarea. What would be another option, I assume a div container that can hold text elements?
Use, <div> with contenteditable attribute.
.textarea{
width:200px;
height:50px;
border:1px solid black;
}
<div class='textarea' contenteditable>
</div>
contenteditable Attribute
Refactored the function but I had to guess on some parameters. Used Template Literals which are Strings on steroids -- they should be your best friend dealing with all that text. The method html() is used extensively so markup can be typed or inserted in as a string.
Demo
function writeMessage(message, from = '', reply = '', serverMessage = false, direct = false) {
let tempRx = '';
let chat = $('.chatbox');
let val = chat.text();
if (!serverMessage) {
if (direct) {
console.log(reply);
if (reply) {
chat.html(`${val} <mark>[Whisper to: ${tempRx} ]</mark> ${from}: ${message}<br>`);
reply = false;
tempRx = undefined;
} else {
chat.html(`${val} <mark>[Whisper from: ${from} ]</mark> ${from}: ${message}<br>`);
}
} else {
chat.html(`${val} ${from}: ${message}<br>`);
}
} else {
chat.html(`${val} ${message}<br>`);
}
chat.scrollTop(chat[0].scrollHeight);
}
writeMessage(`Whispering, whisper test, mumble test, <b style='color:red'>belch test</b>, 😫`, `<b style='color:green'>Rusty</b>`, 'reply', false, direct = true);
<form id='main' name='main'>
<fieldset class='chatbox' contenteditable='false'>
<legend>Status: </legend>
</fieldset>
<fieldset class='chatbox' contenteditable>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Why jQuery append() removes words after first blank space in string

I'm trying to dynamically generate a form after an ajax request. Below is the relevant code sample :
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form').append('<label for=' + i + '>' + i + '</label>' +
'<input id=' + i + ' value=' + field + '>');
}
My problem is that, when var i and var field are strings with blank spaces like "Hello world", my label and inputs will be like <label id="Hello" world=""> and <input value="Hello" world="">. However, the label text will be displayed correctly i.e. <label>Hello world</label>.
I've no idea what kind of sorcery that is, but I'll be very grateful for any help. Thanks in advance.
There's a much more robust way of doing this.
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
}
You won't have to worry about the content of the strings as jQuery and the DOM will handle it for you. Not to mention this is much easier to read.
Use " to enclose the attributes.
$('#properties_form')
.append('<label for="' + i + '">' + i + '</label>' +
'<input id="' + i + '" value="' + field + '">');
EDIT
This will break for the cases where the value for i is something like This "works". Best solution is to append as jQuery or JS objects rather than using HTML string just like Daniel's answer.
Following snippet contains the correct fix for this. Updated based on the answer from Daniel.
i = 'Hello "World"';
field = 'Hello "World"s';
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="properties_form"></div>

A simple JavaScript mad lib game

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"

Pass a string parameter in an onclick function

I would like to pass a parameter (i.e. a string) to an Onclick function.
For the moment, I do this:
'<input type="button" onClick="gotoNode(' + result.name + ')" />'
with result.name for example equal to string "Add".
When I click on this button, I have an error that says that "Add is not defined". Since this function call works perfectly with a numeric parameter, I assume that it has something to do with the symbols "" in the string.
How can I fix this problem?
It looks like you're building DOM elements from strings. You just need to add some quotes around result.name:
'<input type="button" onClick="gotoNode(\'' + result.name + '\')" />'
You should really be doing this with proper DOM methods though.
var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
gotoNode(result.name);
});
​document.body.appendChild(inputElement);​
Just be aware that if this is a loop or something, result will change before the event fires and you'd need to create an additional scope bubble to shadow the changing variable.
A couple of concerns for me with respect to using string escape in onClick and as the number of arguments grow, it will become cumbersome to maintain.
The following approach will have a one hop - On click - take the control to a handler method and handler method, based on the event object, can deduct the click event and corresponding object.
It also provides a cleaner way to add more arguments and have more flexibility.
<button type="button"
className="btn btn-default"
onClick="invoke"
name='gotoNode'
data-arg1='1234'>GotoNode</button>
In the JavaScript layer:
invoke = (event) => {
let nameOfFunction = this[event.target.name];
let arg1 = event.target.getAttribute('data-arg1');
// We can add more arguments as needed...
window[nameOfFunction](arg1)
// Hope the function is in the window.
// Else the respective object need to be used
})
}
The advantage here is that we can have as many arguments (in above example, data-arg1, data-arg2, etc.) as needed.
I suggest not even using HTML onclick handlers, and use something more common such as document.getElementById.
HTML:
<input type="button" id="nodeGoto" />
JavaScript:
document.getElementById("nodeGoto").addEventListener("click", function() {
gotoNode(result.name);
}, false);
This is a nice and neat way to send a value or object.
<!DOCTYPE html>
<html>
<body>
<h1 onclick="test('wow',this)">Click on this text!</h1>
<script>
var test = function(value,object) {
object.innerHTML= value;
};
</script>
</body>
</html>
I am guessing, you are creating a button using JavaScript itself. So, the error in your code is that, it will render in this form
<input type="button" onClick="gotoNode(add)" />'
At this current state, add will be considered as an identifier like variables or function calls. You should escape the value like this
'<input type="button" onClick="gotoNode(\'' + result.name + '\')" />'
Try this...
HTML:
<button id="a1" type="button" onclick="return a1_onclick('a1')">a1</button>
JavaScript:
<script language="javascript" type="text/javascript">
function a1_onclick(id) {
document.getElementById(id).style.backgroundColor = "#F00";
}
</script>
Note: be sure of sending arguments between ' ' signs like ('a1') in HTML code
If your button is generated dynamically:
You can pass string parameters to JavaScript functions like the below code:
I passed three parameters where the third one is a string parameter.
var btn ="<input type='button' onclick='RoomIsReadyFunc("+ID+","+RefId+",\""+YourString+"\");' value='Room is Ready' />";
// Your JavaScript function
function RoomIsReadyFunc(ID, RefId, YourString)
{
alert(ID);
alert(RefId);
alert(YourString);
}
Also you can use the grave accent symbol ( ` ) in a string
Try:
`<input type="button" onClick="gotoNode('${result.name}')" />`
For more information, visit MDN and Stack Overflow.
By Chrome, Edge, Firefox (Gecko), Opera, Safari support, but it does not support Internet Explorer.
If the requirement is to reference the global object (JavaScript) in your HTML code, you can try this. [Don't use any quotes (' or ") around the variable]
Fiddle reference.
JavaScript:
var result = {name: 'hello'};
function gotoNode(name) {
alert(name);
}
HTML:
<input value="Hello" type="button" onClick="gotoNode(result.name)" />​
Multiple parameters:
bounds.extend(marker.position);
bindInfoWindow(marker, map, infowindow,
'<b>' + response[i].driver_name + '</b><br>' +
'<b>' + moment(response[i].updated_at).fromNow() + '</b>
<button onclick="myFunction(\'' + response[i].id + '\',\'' + driversList + '\')">Click me</button>'
);
If you need to pass a variable along with the 'this' keyword, the below code works:
var status = 'Active';
var anchorHTML = '' + data+ '';
You can pass a reference or string value. Just put the function inside the double commas "" as per the below snapshot:
If to use for generation of a set of buttons with different parameters of handlers.
JavaScript Closures
let some_button = document.createElement( "button" );
some_button.type = "button";
some_button.onclick = doWithParam( some_param );
function doWithParam( param ){
return function(){
alert( param ); // <-- Your code here
}
}
If we do:
some_button.onclick = foo( some_param );
function foo( param ){
alert( param );
}
then function foo starts after every updating page.
If we do:
for( let i = 0; i < 10; ++i ){
var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
gotoNode(result.name);
});
​ document.body.appendChild(inputElement);​
}
then for all buttons created in the loop, the last value of the parameter is "result.name".
Here is a jQuery solution that I'm using.
jQuery
$("#slideshow button").click(function(){
var val = $(this).val();
console.log(val);
});
HTML
<div id="slideshow">
<img src="image1.jpg">
<button class="left" value="back">❮</button>
<button class="right" value="next">❯</button>
</div>
<!---- script ---->
<script>
function myFunction(x) {
document.getElementById("demo").style.backgroundColor = x;
}
</script>
<!---- source ---->
<p id="demo" style="width:20px;height:20px;border:1px solid #ccc"></p>
<!---- buttons & function call ---->
<a onClick="myFunction('red')" />RED</a>
<a onClick="myFunction('blue')" />BLUE</a>
<a onClick="myFunction('black')" />BLACK</a>
This is work for me:
$(element).attr("onClick", 'functionName(' + "\"" + Object.attribute + "\"" + ')');
Just add \ slash in ()
※Multiple parameters example
"functionName(" + "'" + parameter1 + "','" + parameter2 + "','" + parameter3 + "','" + parameter4 + "','" + parameter5 + "','" + parameter6 + "')"
let task = {....}
<button onclick="myFunction('${task}')">Continue task</button></li>
In Razor, you can pass parameters dynamically:
<a href='javascript:void(0);' onclick='showtotextbox(#Model.UnitNameVMs[i].UnitNameID, "#Model.UnitNameVMs[i].FarName","#Model.UnitNameVMs[i].EngName","#Model.UnitNameVMs[i].Symbol" );'>#Model.UnitNameVMs[i].UnitNameID</a>
If you are using ASP.NET you can use JavaScript:
HTML
<input type='button' value='test' onclick='javascript: EditSelectedOptionName(x,y)' />"
JavaScript
function EditSelectedOptionName(id, name) {
console.log(id);
console.log(name);
}
For passing multiple parameters you can cast the string by concatenating it with the ASCII value. Like, for single quotes we can use ':
var str = "'" + str + "'";
The same parameter you can pass to the onclick() event. In most of the cases it works with every browser.
<style type="text/css">
#userprofile{
display: inline-block;
padding: 15px 25px;
font-size: 24px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #FFF;
background-color: #4CAF50; // #C32836
border: none;
border-radius: 15px;
box-shadow: 0 9px #999;
width: 200px;
margin-bottom: 15px;
}
#userprofile:hover {
background-color: #3E8E41
}
#userprofile:active {
background-color: #3E8E41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
#array {
border-radius: 15px 50px;
background: #4A21AD;
padding: 20px;
width: 200px;
height: 900px;
overflow-y: auto;
}
</style>
if (data[i].socketid != "") {
$("#array").append("<button type='button' id='userprofile' class='green_button' name=" + data[i]._id + " onClick='chatopen(name)'>" + data[i].username + "</button></br>");
}
else {
console.log('null socketid >>', $("#userprofile").css('background-color'));
//$("#userprofile").css('background-color', '#C32836 ! important');
$("#array").append("<button type='button' id='userprofile' class='red_button' name=" + data[i]._id + " onClick='chatopen(name)'>" + data[i].username+"</button></br>");
$(".red_button").css('background-color','#C32836');
}
If you are adding buttons or link dynamically and facing the issue then this may be help. I solved it by this way:
var link= $(contentData1[i]).find("td:first font b a").attr("href",'javascript:onClick=openWin(\'' + tdText + '\')');
I am new to HTML, jQuery and JavaScript. So maybe my code will not be optimized or syntax, but it was working for me.
Not escaping double quotes is the cause of OP's problem. A readable approach to escape double quotes is using backticks (MDN). Here is a sample solution:
my_btn.setAttribute('onclick', `my_func("${onclick_var1}", "${onclick_var2}")`);
You can use this:
'<input id="test" type="button" value="' + result.name + '" />'
$(document).on('click', "#test", function () {
alert($(this).val());
});
It worked for me.
<button style="background-color: gray;color:white;" onclick="displayAlert('the message')">alert</button>
<script>
function displayAlert(msg){
alert(msg);
}
</script>
The following works for me very well,
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<form>
<input type="button" value="ON" onclick="msg('ON')">
<input type="button" value="OFF" onclick="msg('OFF')">
</form>
<script>
function msg(x){
alert(x);
}
</script>
</body>
</html>
You can use this code in your button onclick method:
<button class="btn btn-danger" onclick="cancelEmployee(\''+cancelButtonID+'\')" > Cancel </button>

Categories

Resources