Dice jQuery - random # + replace the text on die - javascript

My very first question. I have a feeling this is something simple, but it's been driving me crazy because I can't find the issue. I've tested the math function with an alert, so I can see that is working but the actual jQuery below doesn't seem to be running to swap the text. Please help!
var dice = 1;
function math(sides){
return Math.floor((Math.random()*sides)+1).toString();
}
$(document).ready(function(){
$("button").click(function(){
var dice = math(6);
alert("Dice now at " + dice);
$("#number").text("dice");
});
});

dice is a variable, so remove quotes
Try this
$("#number").text(dice); // This will replace the current text with new
If #number is text box
$("#number").val(dice); // This will replace the current value with new

Related

How do i get all inputs from div except empry values for jspdf?

Im using jspdf to create a pdf from some divs i have.
There are a lot of inputs,some of them are required,some are not. I need to get only the values that are not empty from my input fields,but i can't make it work,even tho im 90% sure my code should work fine. Here it is:
var doc = new jsPDF();
var i=1;
$("div#home :input[type=text]").each(function(){
i++;
var input = $(this);
if(input.val().lenght>0){
console.log(input);
var text = input.attr('placeholder')+': '+input.val();
doc.setFontSize(10);
doc.text(10, (i*8) + (10),text+"\n");
}
});
doc.save('a4.pdf')
The code above does not work. when i use it,i get nothing for the pdf. if i remove the .lenght>0 it works,but it gets all the empty values so my pdf goes with a lot of blank spaces. i have tried using input.val().>0,input.val().!=='',and none of them works,they all give me the same result.
How can i check properly if my input fields are not null?
This is probably a typo:
input.val().lenght
should be this instead:
input.val().length
You should see an error message in your browser console, because length was misspelled.
I found the answer to my own problem. The code is fine,the problem was in my auto increment variable "i".
var doc = new jsPDF();
var i=1;
$("div#home :input[type=text]").each(function(){
i++;
var input = $(this);
if(input.val().lenght>0){
console.log(input);
var text = input.attr('placeholder')+': '+input.val();
doc.setFontSize(10);
doc.text(10, (i*8) + (10),text+"\n");
}
});
doc.save('a4.pdf')
As you can see above,my variable was outside the "each" loop that was looping trough the non-empty values of my input fields. The loop was fine,but as the "i++" variable was out of the loop,it was couting empty values and giving me blank spaces between the non-empty ones. So the only thing i needed to do was to move my "i" inside the loop. Yes,pretty stupdid error,but it took me hours to find out.

How to set function to start when previous end in Javascript?

Hi I have this script which has one function which fill text value
and another which search this text. It works fine but "searching" function waits only 4 seconds for input. Without delay it doesn't work, because searching will be run without any text. I want to modify it to start function "document.searchform.submit()" when previous function ends, so input is filled. It seems simple but I am new in JS. Thanks.
final_transcript = capitalize(final_transcript);
var queryTextField = document.getElementById("search_query");
queryTextField.value = final_transcript;
//filling input with text
document.getElementById("search_query").value=final_transcript;
//start searching after 4 seconds
setTimeout(function(){document.searchform.submit();}, 4000);
You just call the function at the end of your function
first_function ()
{
alert('whatever');
second_function();
}
You dont need to wait! You can search immediately if the previous value and new value are not same.
if(document.getElementById("search_query").value!=final_transcript)
document.searchform.submit();
Use Jquery as below
$("#search_query").value(final_transcript).promise().done( function() {
document.searchform.submit();
});

How to select something from a textarea. Creating my editor

I've been searching for a few hours, trying with so many different solutions but anything works for me.
I'm building my own text editor in jQuery, but now I'm facing a problem:
I have this code right now:
function bbcode() {
var div = document.querySelector('textarea');
var start = div.selectionStart;
var finish = div.selectionEnd;
var text = div.value.substring(start, finish);
div.value('[b]' + text + '[/b]');
}
And this too:
$('#bold').click(function(evt) { bbcode(); });
#bold is a button and I want that when I click, it adds me the first part of the bbcode ([b]), the text I've already selected and the last part of the bbcode.
But it doesn't work for me. Where's the problem?
Thanks for reading and helping.
PD: I hope I have explained well.
Cheers.
You are assigning it wrongly. value is not a function which accepts parameter. It is instead a property which can be assigned to.
div.value = '[b]' + text + '[/b]'; // setter
DEMO

comparing variable in javascript

I am in a predicament. I have been trying to compare two variables in javascript and then assign a class to parent element if matched. But i am having no success in this. I have searched through all possible codes and tried them but not able to get it working. The code i have written so far is as below:
$('div#encased a').click(function(){
$('ul#filter .current').removeClass('current');
var class_name = ($(this).parent().attr('class').replace('-',' '));
var className = class_name.toString();
alert(className);
$('ul#filter li').each(function(){
/*1st version
var filterValue = $(this).text().toLowerCase();
var filterValstr = filterValue.toString();
alert(filterValstr);
if(filterValstr==className)
{
alert("match!")
$(this).parent().addClass('current');
}*/
/*2nd version*/
if($(this).text().toLowerCase() == class_name)
{
$(this).parent().addClass('current');
}
/*this works which according to me means it is not entering the if clause
else{
$(this).parent().fadeOut('slow').addClass('hidden');
}*/
});
});
As per my knowledge the value is not going inside the if command at all as i tried using else function and that works. I am sure theres some silly error i am doing. I have tried 2 methods here and i have commented one but presented both of them here to know if any of them should be correct.
Basically on click of an image in my div#encased element the class name of the image is taken and then compared with the text in the filter menu above. If it matches the matched filter text should be assigned the class of current. Hope you are getting what i am trying to explain. Please help. thanks
Your code isn't clear, and kind of a spaghetti one, but maybe your problem is with white spaces, try trim them
var filterValue = $.trim($(this).text().toLowerCase());
And you should know that string.toString() return the string...
Example:
var str = "bla bla bla";
alert(str.toString === str); // true!

Append to a webpage in javascript

What I want to do is that: a webpage with continuously updating content. (In my case is updating every 2s) New content is appended to the old one instead of overwriting.
Here is the code I have:
var msg_list = new Array(
"<message>Hello, Clare</message>", "<message>Hello,Lily</message>",
"<message>Hello, Kevin</message>", "<message>Hello, Bill</message>"
);
var number = 0;
function send_msg()
{
document.write(number + " " + msg_list[number%4]+'<br/>');
number = number + 1;
}
var my_interval = setInterval('send_msg()', 2000);
However, in both IE and Firefox, only one line is printed out, and the page will not be updated anymore. Interestingly in Chrome, the lines are being printed out continuously, which is what I am looking for.
I know that document.write() is called when the page is loaded according to this link. So it's definitely not the way to update the webpage continuously. What will be the best way to achieve what I want to do?
Totally newbie in Javascript. Thank you.
Lily
I would have a div or some other container, like this:
<div id="msgDiv"></div>
Then write to it like using .innerHTML, like this:
var msg_list = new Array(
"<message>Hello, Clare</message>", "<message>Hello,Lily</message>",
"<message>Hello, Kevin</message>", "<message>Hello, Bill</message>"
);
var number = 0;
function send_msg()
{
document.getElementById("msgDiv").innerHTML += number + " " + msg_list[number%4]+'<br/>';
number++;
}
var my_interval = setInterval(send_msg, 2000);
You can see a working example of this here
You can append to the innerHTML property:
var number = 0;
function send_msg()
{
document.getElementById('console').innerHTML += (number + " " + msg_list[number%4]+'<br/>');
number = number + 1;
}
This code will append the message to an element with an id of console, such as
<div id="console"></div>
By the way, it is bad practice to call setInterval with a string.
Instead, pass the function itself, like this:
var my_interval = setInterval(send_msg, 2000);
I would start by looking at the jQuery library. This will save you a lot of pain.
What you want to do is keep inserted lines into a table, using eg:
$('table tbody').append('<tr><td>some value</td></tr>');
This would be an excellent opportunity for you to learn a little DOM programming.
Using the DOM to update the page should result in less overhead than simply concatenating more HTML into it. Find the node you want to put the updates into, and do an appendChild on each subsequent addition.
The answers to this question may be helpful: What's a simple way to web-ify my command-line daemon?

Categories