I'm trying to learn jQuery, but it's coming slowly as I really don't know any JavaScript.
My site is in VB.NET and I'm putting jQuery code on both my actual .ascx UserControl and in a separate file (something like myscripts.js). This is because I'm using webforms as I still don't know MVC well enough to implement it, so I have to get the clientID's on the page.
What I would like to do is the following:
Grab text from a textbox and make it all lowercase
Get the username from the login info. I've done this like so on my actual page:
var userName = "<%=Split(System.Web.HttpContext.Current.User.Identity.Name.ToLowerInvariant, '|')%>";
Check to see if the username is in the text. If it IS in the text, I want to set a variable to "false", othewise to true.
How do I do this?
I am completely ignorant of the ASP.NET side of it, but as far as jQuery and Javascript....
To get the value of a text field, you use the jQuery function val():
var value = $('#mytextbox').val();
To turn a string to lower case, you use the string method toLowerCase():
var value = $('#mytextbox').val().toLowerCase();
Since val() returns a string we can throw that at the end.
To check if a string is within another string, you use the string method indexOf():
var needle = 'Hello';
var haystack = 'Hello World';
var match = haystack.indexOf(needle); // -1 if no matches, 0 in this case
Another thing to remember is that ASP.NET renames all your control ID's. To access your controls in JavaScript, you should use the following in place of the Control ID <%= txtUserName.ClientID %>.
In jQuery, here is what my selector would look like for a textbox with the ID "txtUserName".
$('#<%= txtUserName.ClientID %>')
Enjoy,
Zach
var userName = "username as it comes out of your web app";
// stuff happens
var $myTextbox = $('#ID_of_textbox');
var userNameIsContained = $myTextbox.val().toLowerCase().indexOf(userName) >= 0;
Short explanation:
$('#ID_of_textbox') // fetches the jQuery object corresponding to your textbox
.val() // the jQuery function that gets the textbox value
.toLowerCase() // self explanatory
.indexOf() // returns the position of a string in a string (or -1)
See the JavaScript String object reference at w3schools.
Alternative (to check if the textbox value equals the username):
var userNameIsEqual = $myTextbox.val().toLowerCase() == userName;
The basics of JQuery are like so: Find a list of dom elements, and perform actions on them.
In your case, you should start off by finding the dom element that is your testbox. For example's sake, we'll choose $('#userName'). The selector # means "id" and together with the name "userName" it finds all elements with the id of "userName". (Ids on a page should be unique if you're following best practices.)
Once you have that list (in this case, a list of one element), you can ask it what the value is.
$('#userName').val()
This gets you the value of the value="" attribute of the input tag.
You can then assign it to a variable and use standard javascript String functions to do the rest!
function checkLogin(userName){
return $('#mytextbox').val().toLowerCase() == userName
}
if ($("#textBoxID").val()) != "") { /*Do stuff*/ }
Related
I'm quite new to coding. My goal is to make a simple "daily planner" page where you can save text in each line. I was trying to do this via local.storage, but I'm not quite sure what I'm doing wrong.
I've tried get vs setitem (which I'm not sure if there's a difference) I tried renaming my elements.
div.text(dailyPlanner[i].hour);
let textbox = $("<textarea>");
textbox.attr("data-hour", dailyPlanner[i].line);
textbox.addClass("col-8 col-md-10 description");
textbox.val(dailyPlanner[i].text);
if (currVal !== null) {
localStorage.setItem(textbox, line);
let textbox = localStorage.setItem(textbox)
}
The key needs to be a string so make the key "textbox" and also, what is the value of currVal? Can you confirm it isn't null?
I see two problems in your setIem call:
You are using an html node as a key (textbox) while you should use a string
You are using line as a value, which is undefined in your present code.
So you can try this instead, or adapt this to your case.
localStorage.setItem(dailyPlanner[i].text, dailyPlanner[i].line);
First of all, lets say I have about 10 divs that are hidden and have the ID's as "modal1", "modal2", "modal3", etc... Using an ajax request, the data returned contains an ID number, lets say it is 7.
In previous tasks, I have used the javascript eval function but this does not work. I wish to append the received data to the correct modal div.
var newdataobj = JSON.parse(newdata);
var ResponseDiv = "#modal" + newdataobj.ID;
$(eval(ResponseDiv)).append(newdataobj.DataToAdd);
This doesn't work and the script stops working at this point. I have also tries using the JQuery version of eval, but that did not work either.
You don't need to use eval() here, use just $(ResponseDiv).append(newdataobj.DataToAdd);
ResponseDiv is already a string and that is what you need for the selector.
Try this to confirm you have the right ID:
var newdataobj = JSON.parse(newdata);
var ResponseDiv = "#modal" + newdataobj.ID;
alert(ResponseDiv); // or console.log(ResponseDiv); - to doublecheck you have the right ID
$(ResponseDiv).append(newdataobj.DataToAdd);
ResponseDiv is already a string containing exactly what you want.
You don't want eval at all.
How do I rewrite an href value, using jQuery?
I have links with a default city
parks
malls
If the user enters a value into a #city textbox I want to replace Paris with the user-entered value.
So far I have
var newCity = $("#city").val();
Given you have unique href values (?what=parks, and ?what=malls) I would suggest not writing a path into the $.attr() method; you would have to have one call to $.attr() for each unique href, and that would grow to be very redundant, very quickly - not to mention difficult to manage.
Below I'm making one call to $.attr() and using a function to replace only the &city= portion with the new city. The good thing about this method is that these 5 lines of code can update hundreds of links without destroying the rest of the href values on each link.
$("#city").change(function(o){
$("a.malls").attr('href', function(i,a){
return a.replace( /(city=)[a-z]+/ig, '$1'+o.target.value );
});
});
One thing you may want to watch out for would be spaces, and casing. You could convert everything to lower case using the .toLowerCase() JavaScript method, and you can replace the spaces with another call to .replace() as I've down below:
'$1'+o.target.value.replace(/\s+/, '');
Online Demo: http://jsbin.com/ohejez/
$('a').attr("href", "/search/?what=parks&city=" + newCity);
As soon as a key is released within the #city input field, the href will be updated.
$('#city').keyup(function(){
$('a').attr('href','/search/?what=parks&city='+$(this).val());
});
Like this:
var newCity = $("#city").val();
$('a').attr('href', '/search/?what=parks&city=' + newCity);
EDIT: Added the search string
Is there an equivalent function in JavaScript or jQuery similar to strpos in PHP?
I want to locate a string inside an element on a page. The string I'm looking for is:
td class="SeparateColumn"
I would like something where I can run it like this to find:
if $("anystring")
then do it
I assume you mean check whether a string contains a character, and the position in the string - you'd like to use the indexOf() method of a string in JS. Here are the relevant docs.
Okay, so you'd like to search the whole page! The :contains() selector will do that. See the jQuery docs for :contains.
To search every element in the page, use
var has_string = $('*:contains("search text")');
If you get jQuery elements back, then the search was a success. For example, on this very page
var has_string=$('*:contains("Alex JL")').length
//has_string is 18
var has_string=$('*:contains("horsey rodeo")').length
//has_string if 0. So, you could an `if` on this and it would work as expected.
You don't need jquery for this -- plain old Javascript will do just fine, using the .indexof() method.
However if you really want an exact syntax match for PHP's strpos(), something like this would do it:
function strpos (haystack, needle, offset) {
var i = (haystack+'').indexOf(needle, (offset || 0));
return i === -1 ? false : i;
}
Note: This function taken from here: http://phpjs.org/functions/strpos:545
JSFiddle
Update: clarified question (I hope)
Hi.
I'm developing a plugin in Wordpress and I'm outputting elements according to user privileges A and B.
In case of A, I ouput element "Foo".
In case of B, I output element "Bar".
Up till now, I haven't checked if an element exists before I try to retrieve the value.
This of course gives me a javascript error in some browsers (like IE7).
I've looked at using the typeof() function:
if(typeof(element) == 'undefined') {
//do something...
}
I'm also using jQuery. So one solution could be using this:
if ($("#mydiv").length > 0){
// do something here
}
Using the above methods, makes me having to check each element before trying to retrieve any values.
The "ideal" solution would be to get values based on user privileges. E.g:
if (userPriv == A) {
//get values from element 'Foo'
}
This way I can check once, and do the data gathering. The only solutions I can think of are setting the value of a hidden input element or use cookies.
<input type="hidden" id="userPriv" value="A" />
The other solution would be adding a value to the cookie.
setcookie("userPriv", "A");
Unfortunately, this last option gives me a warning message saying that cookie must be set in header (before html output). I think it's because I'm doing this in Wordpress.
I'm looking for opinions on which method is "the best way" to accomplis this.
Forgive me if I'm missing something, but checking for a DOM element in javascript is usually pretty easy.
var elementA = document.getElementById('id_of_a');
var elementB = document.getElementById('id_of_b');
if (elementA) {
//...
} else if (elementB) {
//...
}
The key is the if statement. getElementById will return nothing null if the element is not found, which will evaluate to false in the if statement.
Alternatively, if you don't really want to check for existence of individual DOM elements, can you send the users priv in a hidden input and act on that? That's a cookie free way of sending values clientside. Something like (edited to have jQuery code instead)
<input type="hidden" id="userPriv" value="A" />
...
var priv = $('#userPriv').val();
if (priv == 'A') {
//...
}
I'd still recommend checking for individual elements over checking a hidden input. It seems cleaner to me, more along the unobtrusive lines
You can use object as associative array:
var map = new Object();
map[A.toString()] = new Foo();
map[B.toString()] = new Bar();
In that case is much simpler to check and you will avoid "spaghetti code".