This code below works in every other browser bar IE. The code basically looks lets the uder pick a card, if it has, it chooses another card that hasn't been picked, and then adds it too an array. Unfortunately its not working in IE. No console errors.
Does anyone have any ideas?
Thanks
function getCard(clicked_id)
{
$("#frontCard").animate({
height:"-=600",
width:"-=250",
},1000,'easeOutElastic');
$("#frontCard").css("opacity",0);
clicked_id = "#" + clicked_id;
$(clicked_id).animate({ opacity: 0, left: "700px" }, 'slow');
$("#frontCard").animate({
height:"+=400",
width:"+=250",
},1000,'easeOutElastic');
$("#frontCard").css("opacity",1);
var newCard= Math.floor((Math.random()*13)+1);
var newSuit= Math.floor((Math.random()*4)+1);
var currentCard;
var x=document.getElementById("pick");
var rules=document.getElementById("rules");
var kings=document.getElementById("kings");
var currentCards=document.getElementById("currentCard");
if (cardsPicked.indexOf(numbers[newCard-1] + " " + suits[newSuit-1])== -1){
if (numbers[newCard-1]=="K" && king<4){
king=king+1;
}
if(king==4){
king= "All kings found!";
alert("Fourth king picked. Down the jug!");
}
cardsPicked.push(numbers[newCard-1] + " " + suits[newSuit-1] );
for (count=0; count<cardsPicked.length; count++)
currentRule = cardRules[newCard-1];
x.innerHTML=cardsPicked;
currentCards.innerHTML=numbers[newCard-1] + " " + suits[newSuit-1];
rules.innerHTML=currentRule;
kings.innerHTML=king;
}else{
getCard();
}
}
{
height:"-=600",
width:"-=250",
}
{
height:"+=400",
width:"+=250",
}
Remove the trailing , in each of your comma separated values in Objects.
I don't see the click event. But may be it helps:
Never overwrite the running event with innerHTML (in IE <10).
Related
I am a noob here in JS and I am doing my homework making a simple color guessing game. So far everything works as far as the criteria goes.
My only problem is that I can't figure out how to make it so that the background changes instantly upon user input (Right after clicking [OK] at the Prompt). As of now with the code below, the background changes only after clicking [OK] in the Congrats alert..I am pretty sure it's possible because my prof showed in the lecture an example he did where the background color changed right after guessing the correct color!
Also, it would be nice if any pros out there could give me suggestions on polishing my code. I have a feeling that it is messy and too complex than what its trying to achieve..Heh..
PS: I know that js logic should be separated in the page but my prof insisted we do this exercise with the script inline!
Thank you!
<body onload="doGame()">
<script>
var myBody = document.getElementsByTagName("body")[0];
var target;
var answer;
var guessInputText;
var guessInput;
var finished = false;
var guessAmount = 0;
var colors = ['Salmon', 'Tomato', 'Moccasin', 'Peru', 'Olive', 'Teal', 'Navy', 'Thistle', 'Beige', 'Gray'];
var colorsSorted = colors.sort();
var colorsSortedString = colors.join(', ');
function doGame() {
var randomColorNum = Math.random() * 10;
var randomColorNumInt = Math.floor(randomColorNum);
target = colors[randomColorNumInt + 1];
answer = target.charAt(0).toLowerCase() + target.slice(1).toLowerCase(); //makes sure answer is in lowercase
alert("The answer is " + target + " or " + answer); //for debugging
while(!finished) {
guessInputText = prompt('I am thinking of one of these colors:\n\n' +
colorsSortedString + '\n\n' +
'What color am I thinking of?');
guessInput = guessInputText.charAt(0).toLowerCase() + guessInputText.slice(1).toLowerCase(); //converts whatever input into lowercase
guessAmount += 1;
finished = checkGuess(); //checks to see if user input is correct
}
}
function checkGuess() {
if ((colors.indexOf(guessInputText.charAt(0).toUpperCase() + guessInputText.slice(1).toLowerCase()) > -1) == false) {
alert("Sorry, I don't recognize your color.\n\n" +
"Please try again!");
return false;
}
if (guessInput > answer) {
alert("Sorry, Your guess is incorrect!\n\n" +
"Hint: Your color is alphabetically higher than mine.\n\n" +
"Please try again!");
return false;
}
if (guessInput < answer) {
alert("Sorry, Your guess is incorrect!\n\n" +
"Hint: Your color is alphabetically lower than mine.\n\n" +
"Please try again!");
return false;
}
myBody.style.background = answer;
alert("Congratulations! You have guessed the color!\n\n" +
"It took you " + guessAmount + " guesses to finish the game!\n\n" +
"You can see the color in the background.");
return true;
}
</script>
</body>
If you want to modify the background before the [OK] on congrats prints, you just have to move this line
myBody.style.background = answer;
But.. Testing your snippet, the background change right after I press OK on the guess color prompt.
So what do you want exactly ? Can you give us an example step by step ?
I'm using
http://davidstutz.github.io/bootstrap-multiselect/ for creating bootstrap multiselect controls in my webpage.
The below fiddle link with static data is what I want to achieve using dynamic data:
https://jsfiddle.net/DROCKS/mrmLrsad/4/
//please refer the fiddle
The search option works fine in case the values of the select box are static, but if they are dynamically created, the multiselect gets created. However the search filter is not working in this case. However the my code is similar to the fiddle below, the only difference being that the search filter part doesn't work in my actual code, but works in this fiddle.
fiddle link with dynamic data.
https://jsfiddle.net/DROCKS/mrmLrsad/5/
//please refer the fiddle
This is my code.
HTML code
<select id="lstFieldList" ></select>
jQuery code [Updated]:
function uncheckFields(field_id)
{
$('#' + field_id).multiselect('deselectAll', true);
}
//json_obj is the value from the fiddle.
createMultiSelectBox(json_obj);
//this function creates the multiselect
function createMultiSelectBox(json_obj)
{
var element_String = "";
var default_ele_set = 0;
var def_element_first = "1"; //if the first Y flag should be considered
var def_element_last = "n"; //if the last Y flag should be considered
var def_element = def_element_first; //change the value here to toggle between default selection
var tmp = [];
for (var key in json_obj)
{
var val = json_obj[key];
//alert("Key: " + key);
var chk_box_ctr = 0;
var element;
for(var child_key in val)
{
//alert("key: " + child_key + "\nvalue: " + val[child_key]);
var default_value = child_key.split(",")[7];
//alert("default_value: " + default_value);
if(!chk_box_ctr)
{
g_max_PageSize = child_key.split(",")[8];
//alert("g_max_PageSize: " + g_max_PageSize);
}
if(def_element == def_element_first)
{
if(default_value == "Y" && !default_ele_set)
{
//element_String += '<option value="' + child_key + '" selected="selected">' + val[child_key] + '</option>';
element = {"label": val[child_key],"value":child_key};
}
else
{
//element_String += '<option value="' + child_key + '">' + val[child_key] + '</option>';
element = {"label": val[child_key],"value":child_key};
}
}
else
{
if(default_value == "Y")
{
//element_String += '<option value="' + child_key + '" selected="selected">' + val[child_key] + '</option>';
element = {"label": val[child_key],"value":child_key};
}
else
{
//element_String += '<option value="' + child_key + '">' + val[child_key] + '</option>';
element = {"label": val[child_key],"value":child_key};
}
}
tmp.push(element);
}
if(def_element == def_element_last)
{
uncheckFields('lstFieldList');
}
}
//$('#lstFieldList').append(element_String);
//$('#lstFieldList').multiselect('rebuild');
$("#lstFieldList").multiselect('dataprovider', tmp);
$('#lstFieldList').multiselect({
maxHeight: 200,
buttonWidth:"100%",
enableFiltering:true,
enableCaseInsensitiveFiltering:true,
/*maxHeight: 200,
enableCaseInsensitiveFiltering: true,
//enableFiltering: true,
onChange: function(option, checked, select) {
alert('Changed option ' + $(option).val() + '.' + "\nchecked: " + checked + "\nselect: " + select);
if(checked)
{
//uncheckFields('lstFieldList');
}
else
{
uncheckFields('lstFieldList');
}
}*/
});
var elem = $('#lstFieldList').next();
elem.attr('class',(elem.attr('class') + ' open'));
}
What could be the problem? because the same code is present in both the files.
Any help would be appreciated.
Thanks in advance.
create an array var tmp = [];
create a json like this while looping for option
element = {"label": this.Name,"value":this.id};
and push each element to tmp
tmp.push(element);
and pass this tmp array to multi select
$("#lstFieldList").multiselect('dataprovider', tmp);
and add multiselect to dropdown by
$("#lstFieldList").multiselect({
maxHeight: 260,
buttonWidth:"100%",
enableFiltering:true,
enableCaseInsensitiveFiltering:true,
});
I actually found out what was causing the unusual behavior in the code related to the bootstrap multiselect plugin. The code given to me by Anoop was right, I also tried various different codes related to the same plugin in the past months, but I later drop the idea to use the plugin.
Then lately last week while reworking on the same code, I identified that I had included some js script files in my html page. So I tried commenting out each include statement for the files in my html to identify which one was causing the issue. So on doing so I reached at a particular js file.
Once the file was identified, I just needed to find out which function was causing the problem to the suggestion logic of the plugin. So to identify this, I kept on commenting/removing the functions till I arrived to the function that caused the issue. There was a code related to window.setTimeout. It was due to this function that the existing suggestion logic was not working as the code was coming into this block. So I later added some flagging logic to avoid running this function in my case.
Thanks a lot all for your inputs.....
I have a small piece of code that is writing some values into a textarea inside a form. The write whenever I click a button. However if I click the button more than once they will write over and over. I need to be able to click the button multiple times (for example if the user changes a value) and have the values that I am writing simply refresh rather than repeat. Here is what I have...
var endwallPanelLengths = [totalHeightInches];
var i = 0;
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
document.getElementById("test83").value += "4 - " + endwallPanelLengths[i] + "\n";
i++;
}
When I click the button the first time the values are correct however they write again after everytome i click it?
In this line:
document.getElementById("test83").value += "4 - " + endwallPanelLengths[i] + "\n";
you're appending a value to test83. Presumably (since I can't see your html!!!) you just need to remove the + from the +=.
EDIT: in case you want to append all of the values in your loop, and nothing else, simply clear the value before you enter your loop and leave the +=
document.getElementById("test83").value = "";
var endwallPanelLengths = [totalHeightInches];
......
I think you want to do the whole iteration when the user change a value. Then you just need to reset the value of the textarea to empty before the loop. Something like this:
var endwallPanelLengths = [totalHeightInches];
var i = 0;
document.getElementById("test83").value = ''; //Reset the value
while (endwallPanelLengths[i] > eaveInches) {
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
document.getElementById("test83").value += "4 - " + endwallPanelLengths[i] + "\n";
i++;
}
I have worked out a demo page. Hope that is what you are after.
Try this:
var endwallPanelLengths = [totalHeightInches];
var i = 0;
document.getElementById("test83").value = '';
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
document.getElementById("test83").value += "4 - " + endwallPanelLengths[i] + "\n";
i++;
}
I'm assuming that all the code is executed eacht time you click the button, am I right ?
you need to implement a clickEventhandler that checks whether or not your texts exists.....
I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here
feel like im coming here way too often to ask questions but yet again I am stuck. I am attempting to select a textarea and allow myself to edit the text in another textarea, which works fine using textboxs but not with textareas. Every time I click on the div container I am getting an undefined result when looking for the textarea. Below is the code.
jQuery
$(".textAreaContainer").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID ).find(':input');
alert(t.attr('id'));
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
//var textboxId = $('div.textAreaContainer').find('input[type="textArea"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" Textarea shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
t.attr('id') should be returning textbox1(or similar) but instead just returns undefined.
I have tried .find(':textarea'),.find('textarea'),.find(text,textArea),.find(':input') and quite a few others that I have found through google but all of them return undefined and I have no idea why. A demo can be found here, http://jsfiddle.net/xYwaw/. Thanks in advance for any help guys, it is appreciated.
EDIT: Below is the code for a very similar example I am using. This does what I want to do but with textboxs instead of textareas.
$('#textAdd').live('click',function() {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Textbox " + textBoxCounter + " <br><div id='container" + counter + "' class='container'><li><input type='text' id='textBox" + textBoxCounter +"' name='textBox" + textBoxCounter + "'></li></div></br>";
document.getElementById("identifier").appendChild(newdiv);
textBoxCounter++
counter++;
});
$(".container").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID).find('input');
alert(divID);
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
alert(t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
// var textboxId = $('div.container').find('input[type="text"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" textbox shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
First up remove the second parameter, 'div', from the first line:
$(".textAreaContainer").live('click','div', function(){
...to make it:
$(".textAreaContainer").live('click', function(){
Then change:
var t = $('#' + divID ).find(':input');
...to:
var t = $(this).find(':input');
Because you already know that this is the container so there's no need to select it again by id. Also the id attributes that you're assigning to your textarea containers have a space in them, which is invalid and results in your original code trying to select the element with '#textAreaContainer 0' which actually looks for a 0 tag that is a descendant of #textAreaContainer. So fixing the code that creates the elements to remove that space in the id is both a good idea in general and an alternative way of fixing this problem.