Get items according to the first letter - javascript

I am trying to get items according the first letter e.g if the items first letter is A I wand that item to appear in divA e.t.c
my code:
function onS() {
var lstString = "";
var Enum = listItems.getEnumerator();
while (Enum.moveNext())
{
var currentItem = Enum.get_current();
lstString += "<br/>" + currentItem.get_item("Title").substring(0,1);//here I check the first letter.
if (lstString = "A") {
$("#divA").html(); //here I want to get that item
}
}
}

If I understand your question, you can do it like this :
if( currentItem.get_item("Title").substring(0,1).toUpperCase() == 'A' )
// or
if( currentItem.get_item("Title")[0].toUpperCase() == 'A' )
Note : You need to use == instead = into an if condition.

var word = 'Aword';
var firstLetter = word[0];
var selector = '#div' + firstLetter;
var container = $(selector);
container.html(word);
Do you mean something like that?
Here is the working example: http://jsfiddle.net/9rky2nwh/

Related

JS : press enter and go to the next input

(Sorry if my english is bad)
I try to make a little game where you have to answer question in inputs. When you valid with the key "Enter", next input appear, and a new question in.
It is complicated to explain, so I leave you the test URL : nicolaslorand.com/bac.php
Here is my a part of my code :
var i = 1;
var j = 2;
$('#input'+i).keypress(function(event) {
console.log('input actuel :'+i);
console.log('input suivant :'+j);
if (event.which == 13) {
verification();
console.log("Touche entrée");
}
});
function verification(){
document.getElementById('input'+j).style.display = "block";
var index = $(".inputform").index(this) + 1;
$(".inputform").eq(index).focus();
var recup = document.getElementById('input'+i);
var verif = recup.value.toUpperCase();
var divLettre = document.getElementById('lettre');
var premiereLettre = divLettre.innerText || divLettre.textContent;
if ( verif.charAt( 0 ) === premiereLettre ) {
$("#input"+i).addClass('trueanswer');
i++; j++;
scoreTotal++;
console.log(i);console.log(j);
}
else{
$("#input"+i).addClass('falseanswer');
i++; j++;
console.log(i);console.log(j);
}
With this code, when I press enter, next input appear, but I have to write in the first input so that my answer is verified by the function.
You are using this inside function this refers to window object. i think you should use i instead of this
var index = $(".inputform").index(i) + 1;

Adding more classes to a javascript function

I'm trying to make a function run several div's in a Q&A accordion, but I can't figure out the right syntax for it to happen. In line 6, the classname 'questionV1' does the job well, but I want the function to run classnames 'questionV2' and 'questionV3' as well. I have tried to add questionV2 + V3, in the same line like this (divs[no].classname=='questionV1, questionV2, questionV3') but it does not work. The javascript looks like this:
function initShowHideDivs()
{
var divs = document.getElementsByTagName('DIV');
var divCounter = 1;
for(var no=0;no<divs.length;no++){
if(divs[no].className=='questionV1'){
divs[no].onclick = showHideContent;
divs[no].id = 'dhtmlgoodies_q'+divCounter;
var answer = divs[no].nextSibling;
while(answer && answer.tagName!='DIV'){
answer = answer.nextSibling;
}
answer.id = 'dhtmlgoodies_a'+divCounter;
contentDiv = answer.getElementsByTagName('DIV')[0];
contentDiv.style.top = 0 - contentDiv.offsetHeight + 'px';
contentDiv.className='answer_content';
contentDiv.id = 'dhtmlgoodies_ac' + divCounter;
answer.style.display='none';
answer.style.height='1px';
divCounter++;
}
}
}
window.onload = initShowHideDivs;
Here are two solution for your problem. One with regex, the other with string comparison.
RegEx Solution:
for(var index in divs){
var div = divs[index];
if(/questionV[123]/.test(div.className)) {
// code here
}
}
String comparison:
for(var index in divs){
var div = divs[index];
if(div.className === 'questionV1'
|| div.className === 'questionV2'
|| div.className === 'questionV3') {
// code here
}
}
also a link to jsfiddle

Javascript: Passing Value of Tag to a Variable

Hope you can help me find a solution to this issue. I have a page with a number of anchor tags that contain an ID with a unique element. Here's a sample of the links:
<a href="#" class="button" id="widget_1"
onclick="$(this).parent().submit(); return false;">Button</a>
<a href="#" class="button" id="widget_2"
onclick="$(this).parent().submit(); return false;">Button</a>
<a href="#" class="button" id="widget_3"
onclick="$(this).parent().submit(); return false;">Button</a>
Below is the code that I tried to create to do collect the values in "id":
var num = [];
for (var i = 0; i<11; i++) {
num[i] = document.getElementsByTagName("id")[i].textContent;
if (num[i] == "widget_1"){ var y = "39.00"; return y;}
else if (num[i] == "widget_2"){ var y = "59.00"; return y;}
else if (num[i] == "widget_3"){ var y = "85.00"; return y;}
else { var y = "0";}
return y; }
What I'm trying to do is capture what's on id and use it to pass it to the array and if the contents match, then return the value of "y". For example, if I click on the second link, then 59.00 is returned. Any help that can be provided will be greatly appreciated.
Thanks,
Ridder
Another Approach
This approach also allows you to remove the onclick events in markup and improve readability, separating behavior from structure. (aka Separation of Concerns)
// put your prices on an array;
var prices = [39.0, 59.0, 85.0];
// match all widget(s) (aka anchors), add click handler.
$("[id^=widget]").click(function(element) {
// calculate the index into prices array based on anchor id.
var index = parseInt(this.id.substring(7)) - 1;
// get the pirce
var price = prices[index];
alert("Price is: " + price);
// here you could call
// this.$parent.submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Button
Button
Button
Pure Javascript
This version without jQuert. Enjoy!
Note: There are some limitations on old browsers (IE < 8 && FF3.0)
// put your prices on an array;
var prices = [39.0, 59.0, 85.0];
var elements = document.querySelectorAll('[id^=widget]');
Array.prototype.forEach.call(elements, function(element) {
var index = parseInt(element.id.substring(7)) - 1;
var price = prices[index];
element.onclick = function(event) {
alert(price);
};
});
Button
Button
Button
Extract just the number
var r = /\d+/;
var s = "add_to_cart_sku_ThisItemA1_CEB";
var index = s.match(r);
alert (index);
Extract a substring (for instance "ItemA1")
var code = "add_to_cart_sku_ThisItemA1_CEB";
var strIndex = code.substring(code.indexOf("Item"), code.lastIndexOf('_'));
alert (strIndex);
if we can define the function :
function MatchID(id) {
var y = "0";
if (id == "widget_1") {
y = "39.00";
} else if (id == "widget_2") {
y = "59.00";
} else if (id == "widget_3") {
y = "85.00";
}
return y;
}
Button
use this
switch(document.getElementById(this.id)){
case "widget_1":
var value = "59.00";
break;
case "widget_2":
var value = "60.00";
break;
case "widget_3":
var value = "61.00";
break;
}
return value;
that is what you need to get the basic job done, now you just need to get the click to go there, if it is another page you will need to know how it was sent and how it is recieved
hope this helps.
document.getElementsByTagName should be given html tag name instead of id and than you can access its id attribute as document.getElementsByTagName("a")[i].id
your code should be as follow :
var num = [];
for (var i = 0; i<11; i++) {
num[i] = document.getElementsByTagName("a")[i].id;
if (num[i] == "widget_1"){ var y = "39.00"; return y;}
else if (num[i] == "widget_2"){ var y = "59.00"; return y;}
else if (num[i] == "widget_3"){ var y = "85.00"; return y;}
else { var y = "0";}
return y; }
document.getElementsByTagName("id") this line in your code is not correct because there's no tags in html that is called `.
To retrieve all of the <a> tags in your document, there's a property of the HTMLDocument interface which is referred to as the document object which represents the entire html document. To retrieve all of the <a> tags. use this.
document.links this method returns a collection of the <a> tags, you can access this collection just like you do an array. For example, to access the first child in that collection.
document.links[0].href to get its href value or to get its id, you do document.links[0].id . Hope this helps

How to get the parameter value from URL in Jquery?

Hi all i have an url where i need to get an parameter from the url
var URL="http://localhost:17775/Students/199/Kishore"
//here from the url i need to get the value 199
this is what i had been trying but the value is null here
function getURLParameter(name) {
return parent.decodeURI((parent.RegExp(name + /([^\/]+)(?=\.\w+$)/).exec(parent.location.href) || [, null])[1]);
};
$(document).ready(function() {
getURLParameter("Students");
//i need to get the value 199 from the url
});
jQuery is not needed for this, though it could be used. There are lots of ways to skin this cat. Something like this should get you started in the right direction:
var URL="http://localhost:17775/Students/199/Kishore";
var splitURL = URL.split("/");
var studentValue = "";
for(var i = 0; i < splitURL.length; i++) {
if(splitURL[i] == "Students") {
studentValue = splitURL[i + 1];
break;
}
}
Here's a working fiddle.
Edit
Based on the comments, indicating that the position will always be the same, the extraction is as simple as:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.split("/")[4];
This is what you're looking for since the URL parameter will keep changing:
http://jsbin.com/iliyut/2/
var URL="http://localhost:17775/Students/199/Kishore"
var number = getNumber('Students'); //199
var URL="http://localhost:17775/Teachers/234/Kumar"
var number = getNumber('Teachers'); //234
function getNumber(section) {
var re = new RegExp(section + "\/(.*)\/","gi");
var match = re.exec(URL);
return match[1];
}
I would do the following:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.match('/Students/(\\d+)/')[1]; //199

Changing picture in javascript form on a click

In this code I get the following error:Exception... "Index or size is negative or greater than the allowed amount" code: "1" nsresult: "0x80530001 (NS_ERROR_DOM_INDEX_SIZE_ERR)". What is causing this? Thanks
function makecard(){
var bodypaint = document.getElementById('minaj');
var recipient = document.getElementById("recipient").value
var radioboxes = document.forms["cardform"].phrase.length
var i = document.getElementById("color").selectedIndex;
var z = document.getElementById("city").selectedIndex;
var tchatche= document.getElementById("color").options[i].text;
var malouba= document.getElementById("city").options[z].value;
for(c=0; c<radioboxes; c++){
if( document.forms["cardform"].phrase[c].checked){
var phrasevalue=document.forms["cardform"].phrase[c].value;
break;
}
}
if(document.getElementById("color").options[i].text === "White"){
bodypaint.style.backgroundColor ="White"
}
if(document.getElementById("color").options[i].text === "Red"){
bodypaint.style.background ="Red"
}
if(document.getElementById("color").options[i].text === "Blue"){
bodypaint.style.backgroundColor ="Blue"
}
var selectedcity = document.forms["cardform"].city.value
var paragraph = document.createElement("div");
paragraph.setAttribute("id","card")
document.body.appendChild(paragraph)
var picture = document.createElement("img")
picture.setAttribute("src", "")
paragraph.appendChild(picture)
paragraph.appendChild(document.createTextNode(phrasevalue + " from " + selectedcity + recipient))
if(malouba== "Paris"){
document.getElementById("picture").src = "paris.jpg"
}
if(malouba== "Venice"){
document.getElementById("picture").src = "venice.jpg"
}
if(malouba== "Rome"){
document.getElementById("picture").src = "rome.jpg"
}
}
document.getElementById("makeacard").onclick = makecard;
It's highly likely that one of the statements is producing a array of 0 elements and then when you try to use it later it freaks out:
var radioboxes = document.forms["cardform"].phrase.length
do a little console.log(radioboxes) on that and see if it comes back undefined or empty

Categories

Resources