For the love of God I am not getting this easy code to work! It is always alerting out "null" which means that the string does not match the expression.
var pattern = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$";
function isEmailAddress(str) {
str = "[email protected]";
alert(str.match(pattern));
return str.match(pattern);
}
As so far i've "found" Yahoo UI library and it fully conforms to my requirements. Also there is jqGrid that i'm using right now. If there are any alternatives?
UPDATE:
Please suggest libraries and don't seek for matching all the requirements listed below. [i'll check it for myself]
My reqs are:
rows adding, deletinig
rows reoder (optionally with drag and drop)
rows selection
inline editing
json data over xhr
(optional) simple integration with backbone.js
disclaimer: there was almost the same question 2 years ago
Ok before i make spaghetti of this code i thought id ask around here. ive made a quiz for an online site.
The answers are stored in an array, and ive a function that checks the answers array to what youve clicked. then it counts them and gives you your score.
but i want to change the clor of the right answer wen the user clicks the score button. so the correct answers are highlighted. something like this https://www.shutterpoint.com/Home-Quiz.cfm (just hit submit at the bottom, no need to do the quiz).
the little answer icon at the side looks flashy but id rather just have the text change color. heres how my questions are formatted
<p>Depth of field is controlled by :?</p>
<p id = "question2"><input type="radio" name="question2" id="Answer1" value = "a" onClick ="recordAnswer(2,this.value)"/> The focal length of the lens. <br/>
<input type="radio" name="question2" id="Answer2" value = "b" onClick = "recordAnswer(2,this.value)"/> The size of the aperture opening. <br/>
<input type="radio" name="question2" id="Answer3" value = "c" onClick = "recordAnswer(2,this.value)"/> The distance between the camera and lens. <br/>
<input type="radio" name="question2" id="Answer4" value = "d" onClick = "recordAnswer(2,this.value)"/> All of these. <br/></p>
and these are the two functions that are called throughout. record answer is called every time the user clicks a button
function recordAnswer(question,answer)
{
answers[question-1] = answer;
}
this is the final button which calculates the score
function scoreQuiz()
{
var totalCorrect = 0;
for(var count = 0; count<correctAnswers.length;count++)
{
if(answers[count]== correctAnswers[count])
totalCorrect++;
}
<!--
alert("You scored " + totalCorrect + " out of 12 correct!");
-->
}
another function is best i think. ive already made attemots at it and know i have to set the color using
document.getElementById('question2').style.color = '#0000ff';
question2 being the p id
i think if i take in the value part of (input type....) ill be able to compare it to the answers array.
but im not quite sure how to do this. any helpers?
maybe something like this
document.getElementById("Answer1").style.color = '#0000ff';
using the id part of the (input type line)
i think i got it actually. ill post my answer in a sec
How do I write a swtich for the following conditional?
If the url contains "foo", then settings.base_url is "bar".
The following is achieving the effect required but I've a feeling this would be more manageable in a switch:
var doc_location = document.location.href;
var url_strip = new RegExp("http:\/\/.*\/");
var base_url = url_strip.exec(doc_location)
var base_url_string = base_url[0];
//BASE URL CASES
// LOCAL
if (base_url_string.indexOf('xxx.local') > -1) {
settings = {
"base_url" : "http://xxx.local/"
};
}
// DEV
if (base_url_string.indexOf('xxx.dev.yyy.com') > -1) {
settings = {
"base_url" : "http://xxx.dev.yyy.com/xxx/"
};
}
Thanks
lets say i use jquery.get to retrive a website to string and how am i gonna select the whole table with class=product from it? $() seem cant work on string ....
Hello everyone.
In Firebug the DOM tab shows a list of all your public variables and objects. In Chrome's console you have to type the name of the public variable or object you want to explore. Is there a way - or at least a command - for Chrome's console to display a list all the public variables and objects? It will save a lot of typing.
Thank you all
Stefanos
i am using modalpopup to enter some value in a textfield. after the value is selected in the modalpopup view, the modalpopup is closed and the value has taken the propriate value. Even if the value is displyed in the textfield, the textfield1.text returns me string empty. when i see the source code (html), i see that even that the textfield is displaying something it hasn't really this value in it, because the appropriate html input field hasn't value yet.
thats the code i use to fill this textfield.
function CloseRequestModal(s)
{
document.getElementById('<%=txtRequest.ClientID%>').value = s;
var mpu = $find('<%=ModalPopupExtender3.ClientID%>');
mpu.hide();
}
Please Help,
Thanks in advance.
Hi,
How can I get the complete html code of the element i'm mouseovering or clicking ?
Using document.onmouseover = function(e){ can I get the full underlying html code of the element which triggered the event ?
Right now, I am able to get the tag name or id or whatever.
What I would like is the whole code.
For example; if I'm mouseovering a table, I would like to get the string : <table><tr><td></td></tr></table>
Is this possible ?
I'm building a phonehap application. I'm using an web sql and everything works fine till data retival.
function getItemGroups(){
var items_groups = new Array();
var db = window.openDatabase("merbokDB", "1.0", "MerbokDB", 5232394);
db.transaction(
function(tx){
tx.executeSql('SELECT * FROM item_groups',[],
function(tx,result){
if(result.rows.length > 0){
var len = result.rows.length;
for (var i=0; i<len; i++){
items_groups.push(result.rows.item(i).item_group);
}
console.log(items_groups.join());
}
}
,errorCB);
},
errorCB);
return items_groups;
}
var myproducts = getItemGroups();
My problem was when I run the code "myproducts" variable is blank. but the I can see
console.log(items_groups.join());
following line printing the values in console. Is I'm wrong in the way I returning?
Hi, i've written this peace of code:
var a=function(){
};
a.name="test";
a.prop="test2";
Now if i debug the code with the console:
console.log(a.name);
console.log(a.prop);
In Firefox i get a.name="test" and a.prop="test2", while in Safari and Chrome i get a.prop="test2" but a.name="".
It seems that there's no way to assign a "name" property on a function in Webkit browsers. Do you know why? But the most important thing is, do you know a workaround for that?
Hi,
I have file upload UI element in which the user will upload images. Here I have to validate the height and width of the image in client side. Is it possible to find the size of the image having only the file path in JS?
Note: If No, is there any other way to find the dimensions in Client side?
I'm building an 'add new row' function for product variations, and I'm struggling with the regex required to match the form attribute keys. So, I'm basically cloning rows, then incrementing the keys, like this (coffeescript):
newrow = oldrow.find('select, input, textarea').each ->
this.name = this.name.replace(/\[(\d+)\]/, (str, p1) ->
"[" + (parseInt(p1, 10) + 1) + "]"
)
this.id = this.id.replace(/\_(\d+)\_/, (str, p1) ->
"_" + (parseInt(p1, 10) + 1) + "_"
)
.end()
This correctly increments a field with a name of product[variations][1][name], turning it into product[variations][2][name]
BUT Each variation can have multiple options (eg, color can be red, blue, green), so I need to be able turn this product[variations][1][options][2][name] into product[variations][1][options][3][name], leaving the variation key alone. What regex do I need to match only the last occurrence of a key (the options key)?
Hi this question is more a consulting of best practice, Sometimes when I'm building a complete ajax application I usually add elements dynamically for example. When you'r adding a list of items, I do something like:
var template = new Template("<li id='list#{id}'>#{value}</li>");
var arrayTemplate = [];
arrayOfItem.each(function(item, index){
arrayTemplate.push(template.evaluate( id : index, value : item))
});
after this two options add the list via "update" or "insert"
----- $("elementToUpdate").update("<ul>" + arrayTemplate.join("") + "</ul">);
the question is
how can I add the event handler without repeat the process of read the array, this is because if you try add a Event before the update or insert you will get an Error because the element isn't still on the DOM.
so what I'm doing by now is after insert or update:
arrayOfItem.each(function(item, index){
$("list" + index).observe("click", function(){
alert("I see the world");
})
});
so the question is exist a better way to doing this??????
I am looking at redesigning my website and was wondering if I could get some opinions.
I know that the rule is usually to design with users without JS first and foremost, but having looked at the stats, it appears 95% of the users online have JS enabled.
Would you recommend designing the website using JS and not bothering about people without it?
I am using the following countdown script which works great, but I can't figure out how to add leading zeros to the numbers (eg so it displays 09 instead of 9.) Can anybody help me out please? Here's the current script:
function countDown(id, end, cur){
this.container = document.getElementById(id);
this.endDate = new Date(end);
this.curDate = new Date(cur);
var context = this;
var formatResults = function(day, hour, minute, second){
var displayString = [
'<div class="stat statBig">',day,'</div>',
'<div class="stat statBig">',hour,'</div>',
'<div class="stat statBig">',minute,'</div>',
'<div class="stat statBig">',second,'</div>'
];
return displayString.join("");
}
var update = function(){
context.curDate.setSeconds(context.curDate.getSeconds()+1);
var timediff = (context.endDate-context.curDate)/1000;
// Check if timer expired:
if (timediff<0){
return context.container.innerHTML = formatResults(0,0,0,0);
}
var oneMinute=60; //minute unit in seconds
var oneHour=60*60; //hour unit in seconds
var oneDay=60*60*24; //day unit in seconds
var dayfield=Math.floor(timediff/oneDay);
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour);
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute);
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute));
context.container.innerHTML = formatResults(dayfield, hourfield, minutefield, secondfield);
// Call recursively
setTimeout(update, 1000);
};
// Call the recursive loop
update();
}
I have an HTML table that should be updated according the file that user uploads.
In other words, I would like user to be able to upload a file, and change the contents of the table according to file content.
The file size can be several MB.
What are my options ?
Do I must to upload the file to a server, or it can be done in client side ? Thanks !
I have to be missing something simple, but I'm really not sure what. I'm not a JS veteran, so this may be an easy answer - sure hope so :).
I have a button that, when clicked, gets JSON data. When a drop-down is changed, I check to see if there is data, if there is, I want to clear it out as the drop-down indicates what data to retrieve when the button is clicked
The Code:
var selected, $locDialog;
var locations = [];
$(function() {
// Save the selected Name
selected = $("#selected option:selected").val();
// Setup Dialog for Locations
$locDialog = $('#location-dialog').dialog({
autoOpen: false
});
// If user changes the selected
// 1. Prompt for confirmation
// 2. If users confirms, clear data
$('#selected').change(function() {
if (locations) {
var confirmed = confirm("Oh Rly?");
if (confirmed) {
// Clear data
var locations;
}
}
});
// When user clicks "Location" Button..
$('.loc-select button').click(function() {
if (!locations) {
$.getJSON("/Controller/JSONAction", { selectedId: selected, pageNum: 1, pageSize: 100 }, function(data) {
locations = data;
$.each(locations, function(index, loc) {
var $tr = $('<tr/>')
.append($('<td/>')
.append('<input type="checkbox" name="TEST-'+index+'" value="'+loc.Id+'"/>'))
.append('<td>' + loc.Name + '</td>');
$("#location-dialog table tbody").append($tr);
});
});
}
$locDialog.dialog('open');
return false;
});
});
Here's the thing, Inside the .click(...) callback, I can see locations is []. Now, when I am in the .change(...) callback, I see locations is undefined.
Any help/insight, as always, is appreciated!
Hi all, I am working on a class assignment in which i need to accomplish the following:
1 User types a list of items into a text box (form field)
2 When the user presses the sort button, the list in the text box is sorted
3 It takes the text from the text box and puts the sorted text back in the text box
Please help!
Hey So I have a question about posting using an XMLHttpRequest. In theory, if I am to post a username and password to an https domain (which I have yet to get working, unfortunately) would the responseText then change to the next website, or should the text fields become filled in? What normally happens is you navigate to this page via browser, enter a username and password, and it uses a POST method when the submit button is clicked, doing some authentication under the hood and returning a different page. I feel like maybe the responseText should even stay exactly the same (which is what happens now), but I don't know as I have no experience with this kind of thing.
this.requests[1].open("POST", "https://" + this.address, true);
var query = "target=%2Fcgi-bin%2FStatusConfig.cgi%3FPage%3Dindex&userfile=&username=user&password=pass&log+in=Log+in";
this.requests[1].setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
this.requests[1].setRequestHeader("Content-length", query.length);
this.requests[1].setRequestHeader("Keep-Alive", 115);
this.requests[1].setRequestHeader("Connection", "keep-alive");
this.requests[1].setRequestHeader("Host", this.address);
this.requests[1].send(query);
this.requests[1].onreadystatechange = onReadyStateChange1;
Then basically onReadyStateChange1 displays the responseText when ready.
Any light that could be shed on what SHOULD be happening with the post and responseText would be very appreciated. As would any advice in getting the new, logged into page.
For further clarification, what I'm trying to do is log in and then return the new page, because the login page displays only log in information/functionality and the page after logging in has a lot of relevant information. I'm not trying to check the credentials as much as I'm trying to get it (the script) to log in so it can access the next page. Granted, the credentials will have to be valid for that.
Thanks all.
I'm trying to use the form web part to do the following
[TextBox Field for typing a product number] [Submit Button]
On Click of submit should go to:
http://www.link.com/product.asp?=[TextBox Field Value]
i have more than 1 divs
wid same ids but one has diplay='block'
and others have display='none'
i want to delete all the divs dat have display='none'
kindly tell the easiest way
If I call the killSwitch() outside the onkeypress, I'll cause an error.
But inside the onkeypress function, I worked just fine.
Why?
// this works fine
var ClassA = function()
{
var doc = document;
// killSwitch();
doc.onkeypress = function(e){ killSwitch(); }
this.killSwitch = function(){ alert('hello world'); }
}
var myClass = new ClassA();