In the document.ready() I have:
$('#menu_indicator').append('<p>' + currPage + ' / ' + pageLimit + '</p>');
pageLimit is always one number that does not change throughout the whole code.
I have it so that when a user clicks a button, it changes currPage to a different number.
(this part is not in document.ready();)
Why doesn't it update it in the indicator?
Any ideas to fix it?
Thanks
The reason your code doesn't work as you expect it to is that you only append it once, it doesn't attach a 'live' handler or something like it.
If you want the indicator to change each time you set a new value for currPage I'd build a function like so:
function setCurrentPage(page) {
currPage = page;
$("#menu_indicator p").html(currPage + " / " + pageLimit);
}
This is of course assuming currPage and pageLimit are declared on a global scope
Demo for Below Code : http://jsbin.com/oruqa3
HTML :
<input type="button" value="click" />
<div id="menu"></div>
JavaScript :
var currPage = 1, pageLimit = 20;
$(function() {
$('input[type=button]').click(function() {
if(currPage <=pageLimit) {
call();
currPage++;
}
});
});
var call = function() {
$('#menu').html('<p>' + currPage + ' / ' + pageLimit + '</p>');
}
Related
I have the following code:
if (secsleft < 10) {
var msg = 'No activity detected in the last 10 seconds.';
if (auth == "true"){
msg += '<br />You will be logged out in <br /><p id="counter">' + secsleft + '</p><br /> more seconds if no activity is detected.';
} else {
msg += '<br />You will be redirected in <br /><p id="counter">' + secsleft + '</p><br /> more seconds if no activity is detected.';
}
if (secsleft < 4) {
//$("#counter").css({"color":"red"});
//$("#counter").css("color", "red");
document.getElementById("counter").style.color = "red";
}
Message('<span id="timer">' + msg + '</span>', 10000);
}
The intent obviously is to change the color of the counter to red when less than four seconds are left. The problem is that the p tag with id="counter" is first created in the IF statement. If I was looking to bind an event to it, I know how to do it. It would be something like:
$(document).on(eventName, "#counter", function() {});
But that doesn't work for attributes. I have tried all kinds of combinations as you can see from the commented code in the inner IF, but none work. Incidentally (and surprisingly to me), I can get the attribute easily, so for example:
alert($("#counter").css("color"));
gives me the right value. So, how does one change the value?
The issue is that you're not actually creating the element until after that if statement, so all of your jQuery selectors and getElementById calls will not find anything on the page since there is nothing with an id of "counter" yet. You've simply made a string that you will later convert into an actual element.
What you need to do is create an actual element and then using a reference to it you can change its attributes before you even put it on the page.
var counter = document.createElement('p');
counter.id = 'counter';
counter.style.color = red;
Or something along those lines. I've shown you the vanilla JS solution here but you can do the same using jQuery:
var counter = $('<p></p>');
counter.attr('id','counter');
counter.css('color','red');
I don't see much jQuery but you did add it as a tag. So why not do something like this?
$("body").find("#counter").css("color", "red");
You can't use document.getElementById() for elements which have not yet been added to the document. That's why it doesn't work.
You could simplify your code a lot.
if (secsleft < 10) {
var color = secsleft < 4 ? 'red' : 'inherit';
var action = auth === 'true' ? 'logged out' : 'redirected';
var msg = 'No activity detected in the last 10 seconds.'
+ '<br />You will be '+ action +' in '
+ '<span style="color: '+ color +'">' + secsleft + '</span>'
+ ' more seconds if no activity is detected.';
Message('<span id="timer">' + msg + '</span>', 10000);
}
I think there is a neater way to achieve what you are looking for rather can adding in the styles using jQuery. Instead it is better to allow your CSS to handle the styles and the jQuery to add in classes where appropriate.
In the below code the <4 check is used to assign a value to a counterClass variable which is then added to you counter element. You can then add a css rule to achieve the red colour.
if (secsleft < 10) {
var counterClass = "";
if (secsleft < 4) {
counterClass = "warning";
}
var msg = 'No activity detected in the last 10 seconds.';
if (auth == "true") {
msg += '<br />You will be logged out in <br />p id="counter" class="' + counterClass + '">' + secsleft + '</p><br /> more seconds if no activity is detected.';
} else {
msg += '<br />You will be redirected in <br /><p id="counter" class="' + counterClass + '">' + secsleft + '</p><br /> more seconds if no activity is detected.';
}
Message('<span id="timer">' + msg + '</span>', 10000);
}
Hope this helps.
The first problem is that you haven't yet added the #counter element to the document, meaning you can't use the document.getElementByID(...); method on it (yet).
To be able to manipulate a element, you would have to add it to the document, to do this you would use:
// appends the new "div" element to the body (I.E: inserts the new element at the end of the body)
$("body").append("<div id='element-id'>Hello World!</div>");
You could also use these methods:
// replaces the "innerHTML" of the "body" element with the new "div" element
$("body").html("<div id='element-id'>Hello World!</div>");
// prepends the new div to the body (I.E: inserts the element as the first child not the last child)
$("body").prepend("<div id='element-id'>Hello World!</div>");
Now, the second problem is that you are getting the value of the CSS property and NOT setting it.
To get the current value of a CSS property you would use this:
$("#element-id").css("property-name")
To change the value of a CSS attribute in jQuery you would use this:
// listen for an event to occur
$(document).on("event-name", function() {
// change a single property of the element
$("#element-id").css("property", "new-value");
});
You could also change multiple properties of the element at once, using a JavaScript object like this:
// listen for an event to occur
$(document).on("event-name", function() {
// change multiple properties of the element using a JavaScript object
$("#element-id").css({
"property-name-one": "new-value",
"property-name-two": "new-value"
});
});
For more information on the jQuery methods mentioned above, visit the links below:
jQuery.fn.html(...);.
jQuery.fn.append(...);.
jQuery.fn.prepend(...);.
jQuery.fn.on(...);.
jQuery.fn.css(...);.
Hope this helps, good luck and all the best.
You will not get element using getElementById which have not yet been added to DOM. you can use inline styles.
if (secsleft < 10) {
var alertColor = "inherit";
if(secsleft < 4) {
alertColor = "red";
}
var msg = 'No activity detected in the last 10 seconds.';
if (auth == "true"){
msg += '<br />You will be logged out in <br /><p id="counter" style="' + alertColor + '">' + secsleft + '</p><br /> more seconds if no activity is detected.';
} else {
msg += '<br />You will be redirected in <br /><p id="counter" style="' + alertColor + '">' + secsleft + '</p><br /> more seconds if no activity is detected.';
}
Message('<span id="timer">' + msg + '</span>', 10000);
}
I am creating a BF4 weapon selector (tells you random weapons/attachments to equip), using the function below, and a link to refresh it (to run the function again), however when the link is clicked, it does not work (and there is no error in console)
Any ideas? JSFiddle
Just to clarify: the text appears, and as a link, however when you click the link (which runs javascript:CreateWeapons(), it does not work, and there is no error in JSFiddle, or in javascript console)
JS:
function Random(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function CreateWeapons() {
document.getElementById('text').innerHTML = ('<a href="javascript:CreateWeapons();">' +
'Primary: ' + Primary +
'<br>' +
'Secondary: ' + Secondary +
'</a>');
}
var Primary = Random(["M16A4", "M16A3", "M416", "None"]);
var Secondary = Random(["None",".44 Deagle"])
CreateWeapons();
// BF4 weapon chooser (using random values)
HTML:
<div id="weapons">
<div id="text"></div>
</div>
If you want the Primary and Secondary weapons to change in each click, you have call Random method inside the CreateWeapons method.
Also it is not good way to use href to call js function, you can use onclick instead of that.
Here is the updated working code for you.
function Random(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function CreateWeapons() {
var Primary = Random(["M16A4", "M16A3", "M416", "None"]);
var Secondary = Random(["None",".44 Deagle"]);
document.getElementById('text').innerHTML = ('<a href="#" onclick="CreateWeapons();return false;">' +
'Primary: ' + Primary +
'<br>' +
'Secondary: ' + Secondary +
'</a>');
}
CreateWeapons();
// BF4 weapon chooser (using random values)
It's better if you create an element and then use it's onclick event to call the function rather using the inline onclick event. Try this,
function Random(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
var aElement = document.createElement("a");
aElement.href="#";
function CreateWeapons() {
var Primary = Random(["M16A4", "M16A3", "M416", "None"]);
var Secondary = Random(["None",".44 Deagle"]);
aElement.innerHTML = ('Primary: ' + Primary + '<br />' + 'Secondary: ' + Secondary);
document.getElementById('text').appendChild(aElement);
return false;
}
aElement.onclick = CreateWeapons;
CreateWeapons();
jsFiddle
My previous problem has been fixed, now I need to ask how to keep a textarea from resetting its input after a form is submitted. Here is the jsFiddle: http://jsfiddle.net/rz4pnumy/
Should I change the form in the HTML?
<form id="form1" method="GET">
(the form does not go into a php file or anything else, i'm using it to submit the textarea input and use the variables I made using jQuery to make a paragraph on the same page)
or something in the JS?
$(document).ready( function () {
$('#form1').on('submit', function (event) {
// If the form validation returns false, block the form from submitting by
// preventing the event's default behaviour from executing.
if (!validate()) {
event.preventDefault();
}
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
var verb1 = $('#verb1').val();
var edibleobject = $('#edible-object').val();
var monster1 = $('#monster1').val();
var adjective3 = $('#adjective3').val();
var monster2 = $('#monster2').val();
var verb2 = $('#verb2').val();
$('body').append(
'<div id="para">' +
'<p>Rain was still lashing the windows, which were now ' + adjective1 +', but inside all looked bright and cheerful. ' +
'The firelight glowed over the countless ' + adjective2 + '' + pluralnoun + ' where people sat ' + verb1 + ', talking, ' +
'doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a ' + edibleobject +' to a ' + monster1 + '.' +
'Fred had "rescued" the ' + adjective3 + ', fire-dwelling ' + monster2 + ' from a Care of Magical Creatures class and it was now ' + verb2 + ' gently ' +
'on a table surrounded by a knot of curious people. </p>' +
'</div>'
);
}
});
function validate() {
var success = true;
$('.input').each(function(i, item) {
if ($(item).val() === "")
{
console.log("Missing textarea input");
success = false;
$(item).attr("style","border:1px solid red;");
//note it will overwrite your element style in all Input class
}
else
{
$(item).removeAttr('style')
// to remove border
}
});
return success;
}
});
The contents get emptied after pressing submit and I only see the completed paragraph for a split second.
You need to prevent the default event handler from executing whether validate passes or not, so you need to remove the if statement around the event.preventDefault() call. The preventDefault is the function that is keeping the from from submitting and re-loading your page.
Also, your Fiddle was not set to jQuery (it was set to no-library) so that may have also been causing you issues during your testing.
Edited for example of what I'm talking about:
$('#form1').on('submit', function (event) {
// block the form from submitting by
// preventing the event's default behaviour from executing.
event.preventDefault();
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
... etc ...
I would use php and set a variable to the GET value of the textarea and set the value of the textarea to that variable
I've got the following jQuery code
$('#rta_ad_yes').click(function(){
$('#rta_ad_pref, #rta_ad_psn').prop('disabled', false);
$('#div_ad_pref, #div_ad_psn').addClass('has-warning');
});
$('#rta_fp_yes').click(function(){
$('#rta_ad_fpref, #rta_ad_fpsn').prop('disabled', true);
$('#div_ad_fpref, #div_ad_fpsn').addClass('has-warning');
});
If you look at the above code it seems i'm doing same coding to achieve the same result.. $('#rta_ad_yes') and $('#rta_fp_yes') in two different pages
sorry to not mentioning my question question how can i declare and call that function provide parameters rather than typing the whole thing again and again.. i dont know how to declare function and reuse it in jquery not very good at jquery
you can try the following code.
function isEmpty (test_obj, element){
if(!test_obj.val().length > 0){
element.addClass('has-warning');
return false;
}else{
element.removeClass('has-warning');
return true;
}
};
and reuse that like below
var x = isEmpty($('#rta_cl_fn'), $('#div_cl_fn'));
hope that helped
Try
.split()
$('#rta_ad_yes', '#rta_fp_yes').click(function () {
var id = (this.id.split('_')[1] == 'fp')? 'f' : '';//get ad or fp from id
//if it's `fp` than add `f` if not than empty string .
$('#rta_ad_' + id + 'pref, #rta_ad_' + id + 'psn').prop('disabled', function(){
return id.length;//return false if 0 and for 1 return true .
}); //make id out of it
$('#div_ad_' + id + 'pref, #div_ad_' + id + 'psn').addClass('has-warning');
});
I believe you want to abstract that in a function?
var disableAndWarn = function (config) {
$("#" + config.id1 + ', ' + "#" + config.id2).attr('disabled', 'disabled');
$("#" + config.id3 + ', ' + "#" + config.id4).addClass('has-warning');
}
Here is a FIDDLE
Edit: Changed your .prop('disabled', true) into .attr('disabled', 'disabled') since I believe that's what you intended.
How can I store multiple values into a single variable and retrieve them into a setTimeout function.
$(document).ready (function (){
div ({'div':'#noo','auto':'true','pos':'top','txt':'hello'});
div ({'div':'#bottom','auto':'true','pos':'bottom','txt':'hi'});
setTimeout (function (){div ({'div':'#top','pos':'top','auto':'true','txt':'new'});}, 4000);
});
function div(obj) {
obj.div; obj.auto; obj.pos; obj.txt; obj.time;
var rec = {};
if(obj.pos == 'top') { $('<ul id="top"></ul>').appendTo('body'); }
if(obj.pos == 'bottom') { $('<ul id="bottom"></ul>').appendTo('body');
$(obj.div).append('<li data-name="' + $.now() + '">' + obj.txt + '</li>');
if(!obj.time) { obj.time = 6000; }
if(obj.auto == 'true') {
setTimeout(function () {
$(obj.div + ' li').fadeOut();
}, obj.time);
}
}
Now, how can I store "data-name" into "rec" variable and retrieve them into setTimeout function for hiding them when "obj.time" is over.
Your code has some mistakes in using jquery selectors. please use # to access by ID
$("#"+obj.div).append('<li data-name="' + $.now() + '">' + obj.txt + '</li>');
also in setTimeout
$("#"+obj.div + ' li').fadeOut();
I am confused in closing brace of second if condition. I closed in that line and its working fine. if you want to retrieve "data-name" to rec, you can use
$("#"+obj.div + ' li').each(function(i) {
$(this).attr('data-name');
});
for single or multiple values. also you can pass to setTimeout as a parameter.
http://arguments.callee.info/2008/11/10/passing-arguments-to-settimeout-and-setinterval/