Generate number on click then pass that to another function - javascript

Say I have some text and a button:
<p id="text-box">placeholder text</p>
<button id="text-btn">New Quote Please.</button>
When I click the button I want something new to appear in the #text-box. So I create an array and some jQuery functions:
var textArr = [word0, word1, word2, word3, word4...];
$(document).ready(function() {
$( "#text-btn" ).click(function(){
x = Math.floor(Math.random()*textArr.length); //This line is the problem.
});
$("#text-box").html(textArr[x]);
});
The idea is when the button is clicked a random number is generated then that number is used to select an item in textArr to display in #text-box. I am fairly certain that the problem lays in the commented line. I think that the x value in the $("#text-btn") function is either not being created at all or is not being passed into the $("#text-box") function.
Thank you for your time.

Show us console try console.log . and text-box html must be inside click event.
$(document).ready(function() {
$( "#text-btn" ).click(function(){
x = Math.floor(Math.random()*quoteArr.length); //This line is the problem.
console.log('check', Math.floor(Math.random()*quoteArr.length))
$("#text-box").html(textArr[x]);
});
});

You have some minor mistakes
Try this...
$(document).ready(function() {
var textArr = ['word0', 'word1', 'word2', 'word3',' word4'];
$( "#text-btn" ).click(function(){
var x = Math.floor(Math.random()*(textArr.length));
$("#text-box").text(textArr[x]);
});
});
DEMO
Update
Some mistakes I found is:
you put the $("#text-box").text(textArr[x]); out side the click function
missing bracket x = Math.floor(Math.random()*textArr.length);, correct format is var x = Math.floor(Math.random()*(textArr.length));
Array elements should have quotes (since it is strings).
define array inside document.ready function.

okay, what's quoteArr? you're referencing the wrong array name! try this.
x = Math.floor(Math.random()*(textArr.length));

Related

Get NaN instead of id value in jquery

I try to get element id using jquery, but instead of id I have a NaN, can anybody help me?
<button class="editResume" type="button" id="editResume1">Edit</button>
$(function () {
$(".editResume").click(function () {
var id = parseInt($(this).attr('id').substring(6));
alert(id);
});
});
You should use 10 instead of 6 since the number is staying at 10th index:
var id = parseInt($(this).attr('id').substring(10));
Fiddle Demo
Another alternative solution here is to apply regex:
$(function () {
$(".editResume").click(function () {
var id = parseInt($(this).attr('id').match(/\d+$/),10);
alert(id);
});
});
Fiddle Demo
var id = parseInt($(this).attr('id').substring(10));
But why do you want do it in this way?
If you want to append some (number or id of the table) in the attribute id always seperate it with some character (say -).
eg. id='editResume-1'. Then in jQuery.
var id = $(this).attr('id').split('-').pop() will give back your number. It works for every case even if you id is id='edit1Resume-1 or id='5-edit-resume-1 or any. Remember to append your required number/id at the end seperated by -
I always prefer this way. May be useful (yn)
If only the number from id value changes you can get it by using
var id = parseInt($(this).attr('id').substring(10));
'editResume1'.substring(6) is actually 'sume1'
You can use slice method also to get the digit if the number is always present at the end
var id = parseInt($(this).attr('id').slice(-1));
JsFiddle
You probably need 10 instead of 6 in substring(indexA[, indexB]) also you can give end index
Live Demo
var id = parseInt($(this).attr('id').substring(10));

How to find td element id with value x?

I need to find exactly that td row which contains value priview '2'
I know the td row first half id, but it is dynamic: MovementNumber_M_* (Where * can be from 1 to Milion)
So need to search all rows from MovementNumber_M_1 to MovementNumber_M_9999 which contains MovementNumber_M_*.value=2 and returning directly that td row id which contained that value.
Can you help me? Thanks in advice.
Right and helpfull answers guaranteed ;)
//EDIT
function DgIdOnClick (e,r){
var MovementNumber = document.getElementById(e).value;
//alert('MovementNumber: '+MovementNumber+' Type :'+r);
var result = $('[id^="MovementNumber_M_"][value='+MovementNumber+']');
result.each(function(){
alert($(this).attr("id"));
});
}
OK value=1 is for init and thats why are alerting all rows but if value is 2 then jq is not finding him WHY ?
The function DgIdOnClick is inicialized #
$( document ).ready(function() {
var SecondDiagnosis=$( "span[id^='lov_Dg2Id_D_']" );
var SpanBlock2=SecondDiagnosis.find('a');
var eventH2=SpanBlock2.attr( "onclick" );
SpanBlock2.attr("onclick", "DgIdOnClick(document.getElementById('MovementNumber_D_'+parentElement.getAttribute('id').substring(12)).id,2);"+eventH2);
var FirstDiagnosis=$( "span[id^='lov_DgId_D_']" );
var SpanBlock=FirstDiagnosis.find('a');
var eventH=SpanBlock.attr( "onclick" );
SpanBlock.attr("onclick", "DgIdOnClick(document.getElementById('MovementNumber_D_'+parentElement.getAttribute('id').substring(11)).id,1);"+eventH);
});
function DgIdOnClick is on other .js file
If i am alerting IN DgIdOnClick alert(document.getElementById('MovementNumber_M_2').value)//MovementNumber_M_2 Then value is 2 but jq is not founding it
This alerts the ID's of each row containing that value
var result = $('[id^="MovementNumber_M_"][value="2"]');
result.each(function(){
alert($(this).attr("id"));
});
http://jsfiddle.net/q8QaG/
Update:
This alerts the id of all inputs with the value of 2, even on input update
$("#button").click(function(){
$('[id^="MovementNumber_M_"]').each(function(){
var value = $(this).val();
if(value == 2){
alert($(this).attr("id"));
}
});
});
http://jsfiddle.net/q8QaG/3/
$('#TableID').find('td').filter(':contains("SOME_TEXT")');
The previous 2 answers have the string encoding similarly incorrect. This should be it:
$('[id^="MovementNumber_M_"][value="2"]');
You can use combination of Attribute Starts With Selector [name^="value"] and Attribute Equals Selector [name="value"]
var myElement= $("[id^='MovementNumber_M_'][value=2]");
As per comment, if you need id use attr()
var myElementId = $("[id^='MovementNumber_M_'][value=2]").attr('id');

Jquery get readout of text area live

I was wondering if I could get a little help. I want to get a live preview of what is in my text area above it.
Each new line in the text area will display as a list above it, so something like this:
test
test2
test3
Text area:
test
test2
test3
How I want it to work is that on load it reads the contents of the text area and displays the contents above in a list. Then when the contents of the text area changes it also changes the list above it.
Here is my code: http://jsfiddle.net/spadez/9sX6X/
<h4>Placeholder</h4>
<ul id="tst"></ul>
<textarea rows="4" cols="50" placeholder="Test" id="test"></textarea>
This is how far I got:
$('#test').bind('input propertychange', function() {
if(this.value.length){
Rerender list to show contents
}
});
This is one of my first scripts so could someone please give me some guidance on how this should be achieved?
Fiddle
var list = $('#tst');
$('#test').on('keyup', function() {
list.empty();
if(this.value.length){
$.each(this.value.split("\n"), function(i, val){
list.append($('<li></li>').text(val));
});
}
});
$('#test').trigger('keyup'); // required to make it do the update onload
Because of my usage of .text(), this will handle special characters such as < and > without a problem. Also note how I have only selected the <ul> a single time, instead of re-selecting it over and over.
Side note: as of jQuery 1.7, .on() is preferred instead of .bind().
is this what you are looking for? http://jsfiddle.net/9sX6X/2/
CODE
$('#test').bind('keyup', function () {
if (this.value.length) {
var inp = this.value.split("\n");
$("#list").empty();
for(var x = 0; x < inp.length; x++){
$("#list").append("<li>"+inp[x]+"</li>")
}
}
});
Hope it helps
You could do this:
$('#test').on('change', function () {
var lines = $(this).val().split('\n');
$('#tst').empty();
for (var i = 0;i < lines.length;i++){
$('#tst').append('<li>' + lines[i] + '</li>');
}
});
Note: this code works on the change event of the textarea, thus you need to click outside of the textarea for the event to fire. If you want to do it on every key press, you should change the event from change to keyup. However, this does lead to far less performance.
You can see the updated fiddle here: http://jsfiddle.net/xv73p/

How to reference an id with brackets in jQuery

I'm painfully new to jQuery and I need to grab the value on change of a text input box with an id of id[2][t] and display that text in a div to be styled later on (also styled with jQuery).
This is the input box code:
<input id="id[2][t]" name="id[2][t]" maxlength="20" type="text">
This is the div I am trying to display it in:
<div id="textpreview"></div>
This is what I have tried, among other variation with no success:
$(document).ready(function() {
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = $('#id\\[2\\]\\[t\\]').text();
$("#textpreview").val(txtval);
});
});
I know the brackets are a problem but they need to remain for other reasons.
Any ideas?
$( document.getElementById( "id[2][t]" ) ).change( function(){
$( "#textpreview" ).text( this.value );
} );
You might consider revising your IDs (though I'm guessing they might be auto-generated). According to this question your IDs are invalid against the spec
Use the attribute selector instead:
var sel = $("[id='id[2][t]']");
sel.change(function() {
$("#textpreview").val(sel.text());
});
Plain Old JavaScript:
var elem = document.getElementById('id[2][t]');
elem.onchange = function()
{
var elem = document.getElementById('textpreview');
elem.removeChild(elem.firstChild)
elem.appendChild(document.createTextNode(this.value));
}
Ahhh... now doesn't that feel better?
You have val and text backwards. Swap them:
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = $('#id\\[2\\]\\[t\\]').val();
$("#textpreview").text(txtval);
});
val is used to get the value of the textbox. text to set the text within the div.
You can further simplify the code by using this instead of re-querying the element.
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = this.value;
$("#textpreview").text(txtval);
});
You can try using the attribute selector instead of the id selector.
$('[id="id[2][t]"]')

get value of inside a tag with jQuery.?

How can by jQuery get value inside tag b?
<span>
<b>hi_1</b>
<b>hi_2</b>
<b>hi_3</b>
<b>hi_4</b>
<span>
I want this output with jQuery: hi_1, hi_2, hi_3, hi_4
Please give me example in jsfiddle.
Are you looking for something like this?
http://jsfiddle.net/ZDYnq/
$(document).ready(function() {
var textArr = [];
$('span b').each(function() {
textArr.push($(this).text());
});
alert(textArr.join(', '));
});
To get the value inside a specific HTML tag in jQuery you can use the text function. This combined with a selector gets the output you're looking for
$('span b').each(function() {
console.log($(this).text());
});
JSFiddle
JSFiddle with commas
This is cool
var x = $("span b").map(function() {
return $(this).text();
}).toArray().join(", ");
Demo here
Discussed here

Categories

Resources