Javascript next button array - javascript

I am unrehearsed in javascript and was hoping for some help with a next button that links to an id based on the array. Here is the array
var baseline_next=new Array();
baseline_next[0]="#one";
baseline_next[1]="#two";
baseline_next[2]="#three";
baseline_next[3]="#four";
baseline_next[4]="#five";
baseline_next[5]="#six";
baseline_next[6]="#six2";
baseline_next[7]="#seven";
baseline_next[8]="#eight";
baseline_next[9]="#nine";
baseline_next[10]="#ten";
baseline_next[11]="#eleven";
baseline_next[13]="#thirteen";
baseline_next[14]="#fourteen";
baseline_next[15]="#fifteen";
baseline_next[16]="#sixteen";
baseline_next[17]="#seventeen";
baseline_next[18]="#eighteen";
baseline_next[19]="#nineteen";
baseline_next[20]="#twenty";
baseline_next[21]="#twentyone";
baseline_next[22]="#twentytwo";
baseline_next[22]="#twentythree";
Basically what I need is, when the next button is clicked first ("0" ~ #one) I need the next buttons id to become two, and when clicked again it needs to become #three. I have no idea how to link an array to a button. The reason I need this to happen is because I am using ajax to .load div contents, so the next button doesn't actually submit, it just becomes a new next button. I dont know if it matters, but here is a part of what the button would cause to happen on click.
$('#one').click(function(){
$("#area").hide("slide", { direction: "left" }, 500);
$("#area").load("test_it.jsp #area");
$("#area").show("slide", { direction: "right" }, 500);
$("#two").show();
});
$('#two').click(function(){
if((document.form1.baseline_01[0].checked || document.form1.baseline_01[1].checked| document.form1.baseline_01[2].checked)
&& (document.form1.baseline_02[0].checked || document.form1.baseline_02[1].checked)
&& (document.form1.baseline_03_native.checked || document.form1.baseline_03_asian.checked|| document.form1.baseline_03_black.checked|| document.form1.baseline_03_pacific.checked|| document.form1.baseline_03_white.checked|| document.form1.baseline_03_other.checked)){
if(document.form1.baseline_03_other.checked && document.form1.baseline_03_other_text.value==""){
alert("Please fill in what other race you concider yourself to be.");
return false;
}else{
$("#area").hide("slide", { direction: "left" }, 500);
$("#area").load("test_it.jsp #area2");
$("#area").show("slide", { direction: "right" }, 500);
$("#three").show();
return true;
}
}else{
alert("Please select an answer for each question.");
return false;
}
});
I must apologize in advanced if my question is hard to follow, I just started coding this year.

I think that you should consider reworking your code a bit to not have this list of IDs and use a single class on all of the elements. It would help to see how your HTML is set up to get the next element based on class as well.
Since you already have this array of doom, though, I guess we'll have to use it. Ideally, you have the same class on each element. Let's say, .number.
$(".number").on('click', function () {
var nextID = baseline_next.indexOf(this.id) + 1;
});
If you can't use .number, then you can do the same thing except with a list of every ID that needs to be bound .. ouch. In the above function, nextID should be the index of the ID that comes after the clicked element.
By the way, IDs can be numbers, and you could even use data-id that contains the number. That would be easier too.

OK I really need to ask why are you doing this, are you sure that creating more than 20 ID's called like that is the better way to do want you want?
Anyways, first of all, you can create the array in a shorthand way:
var baseline_next= ["#one", "#two", "#four", "#five", "#six", "#six2" ..., "#twentythree";
(btw "#six2"? really?)
then do something like this:
var counter = 0; // start for the first one
$("#button").on('click', function () {
var id = counter++;
baseline[id]; // and I don't know what you want to do with this, but here it is!
});

Ancient question. (7 years wowzers). Here is some logic that I used for determining the next item in an array using indexOf. This will also start from the beginning once you reach the end of your array.
let options = [true,false,null];
let current = options.indexOf(this.get('order'));
let next = (current+1 > options.length-1 ? 0 : current+1);
this.set('order', options[next]);

It can be simplified as follows:
let baseline_next = ["#one", "#two", "#three"];
Don't use a var as it behaves unpredictably.
Add a variable count to change the index of the array.
let count = 0;
let baseline_next = ["#one", "#two", "#three"];
$(baseline_next[count]).click(function() {
count++;
});
Or
let count = 0;
let baseline_next = ["#one", "#two", "#three"];
$("#one").click(function() {
$(baseline_next[count]).click();
count++;
});

Related

Get JavaScript Object

I am working client side on a web page that I am unable to edit.
I want to use JS to click on a particular button, but it does not have a unique identifier.
I do know the class and I do know a (unique) string in the innerHTML that I can match with, so I am iterating through the (varying number) of buttons with a while loop looking for the string:
var theResult = '';
var buttonNum = 0;
var searchString = '720p';
while (theResult.indexOf(searchString) == -1
{
theResult = eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum + \"].innerHTML\");
buttonNum++;
}
Now I should know the correct position in the array of buttons (buttonNum-1, I think), but how do I reference this? I have tried:
eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum-1 + \"].click()")
and variation on the position of ()'s in the eval, but I can't get it to work.
You could try something like:
var searchStr = '720p',
// Grab all buttons that have the class 'streambutton'.
buttons = Array.prototype.slice.call(document.querySelectorAll('button.streamButton')),
// Filter all the buttons and select the first one that has the sreachStr in its innerHTML.
buttonToClick = buttons.filter(function( button ) {
return button.innerHTML.indexOf(searchStr) !== -1;
})[0];
You don't need the eval, but you can check all the buttons one by one and just click the button immediately when you find it so you don't have to find it again.
It is not as elegant as what #Shilly suggested, but probably more easily understood if you are new to javascript.
var searchString = '720p';
var buttons = document.getElementsByClassName("streamButton"); // find all streamButtons
if(buttons)
{
// Search all streamButtons until you find the right one
for(var i = 0; i < buttons.length; i++)
{
var button = buttons[i];
var buttonInnerHtml = button.innerHTML;
if (buttonInnerHtml.indexOf(searchString) != -1) {
button.click();
break;
}
}
}
function allOtherClick() {
console.log("Wrong button clicked");
}
function correctButtonClick() {
console.log("Right button clicked");
}
<button class='streamButton' onclick='allOtherClick()'>10</button>
<button class='streamButton' onclick='allOtherClick()'>30</button>
<button class='streamButton' onclick='correctButtonClick()'>720p</button>
<button class='streamButton' onclick='allOtherClick()'>abcd</button>
I would stay clear of eval here, what if the text on the button is some malicious javaScript?
Can you use jQuery? if so, check out contains. You can use it like so:
$(".streamButton:contains('720p')")

JavaScript: image slider changes only once upon clicking

I'm puzzled by the function of my JavaScript image slider since it changes the slide only once upon clicking next (I haven't worked on previous yet, but should be logical enough to re-adjust). The code is given by:
$(".room_mdts").click(function(event){
//get the target
var target = event.currentTarget;
var room = $(target).data("room");
currentIndex = parseInt($(target).attr('data-room'));
//First way, by reuse target (only inside this function)
$('#room_details_holder').show();
//The second, by using selectors
//remove all "selected" classes to all which have both "room" and "selected" classes
$('.room_exp.selected').removeClass("selected");
//add "selected" class to the current room (the selector can also be the target variable)
$('.room_exp[data-room='+room+']').addClass("selected");
});
var currentIndex = 0;
var adjIndex = currentIndex - 1,
items = $('.room_details .room_exp'),
itemAmt = items.length;
function cycleItems() {
var item = $('.room_details .room_exp').eq(currentIndex);
items.hide();
item.css('display','inline-block');
}
$('.room_next').click(function() {
adjIndex += 1;
if (adjIndex > itemAmt - 1) {
adjIndex = 0;
}
cycleItems(adjIndex);
cycleItems(currentIndex);
$('#room_name').text($('.room_exp:nth-child('+(adjIndex+2)+')').attr('title'));
});
$('.room_previous').click(function() {
currentIndex -= 1;
if (currentIndex < 0) {
currentIndex = itemAmt - 1;
}
cycleItems(currentIndex);
$('#room_name').text($('.room_exp:nth-child('+(currentIndex+1)+')').attr('title'));
});
$('#room_name').text($('[style*="inline-block"].room_exp').attr('title'));
});
The reason I had to introduce adjIndex is because without '-1' the slide changed by 2 on the first click, again, no idea why.
The Fiddle: https://jsfiddle.net/80em4drd/2/
Any ideas how to fix that it only changes once? (And also, the #room_name only shows after the click, does not show upon expanding).
Try this I rearranged your code a little bit:
made your currentIndex global and assigned with the adjIndex. If that's ok I will improve my answer:
If you click on the right arrow it goes to the end and comes back to the beginning.
url: https://jsfiddle.net/eugensunic/80em4drd/3
code:
function cycleItems() {
currentIndex=adjIndex;
var item = $('.room_details .room_exp').eq(currentIndex);
items.hide();
item.css('display','inline-block');
}
Okay, great thanks to eugen sunic for the little push that got me thinking!
I have finially cracked all of the pieces, although, I might have some extra unecessary bits of code, duplicates etc, but the functionallity is just perfect!
What I have edited:
I moved one of the closing brackets for the cycleFunction () closing bracket to the end of .click functions, that is to make the variable global (at least for those 3 functions)
I changed the title writing function from: $('#room_name').text($('[style*="inline-block"].room_exp').attr('title'));
to:$('#room_name').text($('.room_exp:nth-child('+(adjIndex+2)+')').attr('title'));
Added a few changes regarding .addClass/.removeClass to the $('.room_details_close').click(function(){.
Now, openning any of the thumbnails shows the title immediately (the right title), clicking '<<' or '>>' changes the slide to next and previous, respectively, while the title changes accordingly. Closing the expanded menu and clicking on a different thumbnail results in re-writing the currentIndex (hence, adjIndex too), so the function starts again with no problem.
Please feel free to use!
The new fiddle is: Fiddle

Event on second and third click

I'm currently in the process of making a website for my band, and one idea I had was that on a specific page, you would see a picture of each band member, and when you hover over it with your mouse the picture would change and you would hear that band member saying something, then when you click on them, they say something else and you'll be redirected to their page.
This alone isn't a problem, but for one member, I want it to take three clicks before you actually get redirected to his page; I also want him to say something different at each click.
So what I'm basically looking for is a way to create different events on the first, second and third click (preferably using javascript).
I hope you guys can help me out, thanks in advance!
Just use variable to count clicks:
var count = 0
$(".test").click(function() {
count++;
if(count == 1) {
$(".test").text("first");
}else if(count == 2){
$(".test").text("second");
}else if(count == 3){
$(".test").text("third");
count = 0;
}
})
http://jsfiddle.net/x83bf1gq/4/
An option could be to create an onclick handler that keeps saying things until all texts in an array of texts are said. Once all the texts have been said, you can just redirect or whatever action you need to be done. Example:
var johnTexts = [
'hello',
'how are you doing',
'come on'
];
var jamesTexts = [
'ready',
'go'
];
var sayTexts = function (texts) {
var i = 0;
return function () {
if (i < texts.length) {
alert(texts[i++]);
} else {
alert('do your redirect or whatever you need');
}
};
}
document.getElementById('john').onclick = sayTexts(johnTexts);
document.getElementById('james').onclick = sayTexts(jamesTexts);
See demo
Simply set an event listener that makes different actions based on a global counter of clicks.
Check this fragment of code:
//set counter
var counter = 0;
var component = document.getElementByID("ID-of-component");
component.addEventListener('mouseover', function(){
//do something
});
component.addEventListener('click', function() {
switch(++counter) {
case 1: /* do something */ break;
case 2: /* do something */ break;
case 3: /* do something */ break;
}
counter = 0; //reset counter
});
Obviously, you have to write this code for each component of your band.

How can I make sure my value was add and exist and then run another code jquery?

You can see the code below, you can enter any value and then append it to the div. I want to add a code that make sure the value appear on the div first and make sure it is exist and then run the code. Because I am using .ajax to make a search function, so I want to make sure the value is exist in the div and the run the .ajax. So, I am thinking about if input_length is greater than current length, but I don't know if that correct or not. because input_length actually is the current length,right? Help, appreciate.
$( "#input" ).keydown(function( event ) {
if ( event.which == 13 ) {
event.preventDefault();
//put input value into div
var value=$('#input').val();
$('#word').append(" " + value);
}
var input_length=$('#word').text.().length();
//I want to code if one word add and exist, then run my .ajax code.
});
.test {display:inline-block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="word" id="word">dog</div>
<input type="text" id="input"/>
This question doesn't make a lot of sense to me, but you can check to see if the word in question exists like this:
// With jQuery
var newWord = $('#input').val();
var wordContainer = $('#word');
if (wordContainer.text().indexOf(newWord) < 0) {
wordContainer.append(' ' + newWord);
}
// Or with plain JavaScript
var newWord = document.getElementById('input').value;
var wordContainer = document.getElementById('word');
if (wordContainer.innerText.indexOf(word) < 0) {
wordContainer.appendChild(document.createTextNode(' ' + word));
}
Both append and appendChild synchronously add the word, so you don't need to check after using them. It's definitely there. ;)

Disable holding the up and down buttons on a jQueryUI spinner

I'm using jQuery 1.7.1 and jQueryUI 1.9.1.
I have a spinner, and every time it changes, a text field will be created or removed to match the number on the spinner. Holding the button will cause the number to change very rapidly, causing a ton of fields to be created or removed.
Not a huge problem since it's client-side, but I just don't like it. So I want to disable the rapid spinning when the user holds the spinner buttons.
I came up with a solution using a function for incremental, which looks like this:
var incrementalFunction = function(numOfSpins) {
if (numOfSpins == 1) {
return 1;
}
return 0;
};
This worked great at first, but caused another issue. Next to each newly created text box, I made a 'remove' button that would remove the element and decrement the spinner. But when I call the stepDown method, for some reason, this calls my incremental function, with an increasing numOfSpins every time it was called. So it would only decrement once.
Anyone have a more straightforward solution to preventing the user from holding the increment/decrement buttons (or the up/down arrows on the keyboard)?
If you upgrade to jQuery UI 1.10, the problem will go away. See https://github.com/jquery/jquery-ui/commit/0d53fbfd0b7651652601b3b8577225ab753aab44 which causes stepUp() and stepdDown() to behave as you'd expect.
If you use the stop event, instead of targeting each increment, you can detect when a selection has been made. Then, you can compare that number to how many are currently there, and determine what to do - remove or add more. Try this:
var targetArea = $("#target_area");
targetArea.on("click", ".remover", function () {
$(this).closest("div").remove();
$("#input1").spinner("stepDown");
});
$("#input1").spinner({
stop: function (event, ui) {
var $this = $(this);
var num = $this.val();
var newTargets = targetArea.find("div");
var difference = num - newTargets.length;
if (difference < 0) {
newTargets.slice(difference).remove();
} else if (difference > 0) {
for (var i = 0; i < difference; i++) {
var newTarget = $("<div><input type='text' /><span class='remover' title='Remove'>×</span></div>");
targetArea.append(newTarget);
}
}
}
});
DEMO: http://jsfiddle.net/PJpUC/1/

Categories