is there such a way? I've had little success in using the .innerHTML method.
Some context, I'm new to Javascript, and I'm trying to make a text RPG as a bit of a fun project using what I know in HTML, CSS, and Javascript... The latter of which I've had not too much experience with yet.
The function would have to modify a element, inserting a snippet that asks for a name for a character, and the form along with a submit button... Then take what they enter and modify a JSON variable that'll essentially function as a character file.
It all has to be done client side as well, if it can be helped... Any way someone might help? Or of not give an outright solution, point me in the right direction?
You can use cookies to store information on the browser, such as a player name. Example is
document.cookie='PlayerName = ThatOneGuy';
You can see more details at https://developer.mozilla.org/en-US/docs/Web_Development/HTTP_cookies
Below, I've written some simple dom manipulation, that creates a form, an input, and when the input loses focus stores whatever is in the input, into either a cookie or localStorage.
There are several things missing, like checking if the input actually had a value, along with zero error checking.
You can find out more about localStorage here, here and here. You can find out more about cookies here.
function init_form(){
var form = document.createElement('form');
var input = document.createElement('input');
input.setAttribute('id', 'player_name');
input.setAttribute('placeholder', ' Enter Characters Name');
input.setAttribute('type', 'text');
form.appendChild(input);
document.appendChild(form); //or document.getElementsByTagName('body')[0].innerHTML += form;
input.addEventListener('blur', store_name_in_local_storage, false);
}
function store_name_in_local_storage(){
var name = document.getElementById('player_name');
//check to see if browser supports local storage if it does, use it, if it doesn't use cookies
if(!window.localStorage){
document.cookie = 'player_name ='+ name;
}else{
localStorage.setItem('player_name', name);
}
}
function get_player_name(){
var name = '';
//retrieve the cookie or local storage name
if(!window.localStorage){
name = document.cookie
}else{
name = localStorage.getItem('player_name');
}
}
Note about the links: Since your new to javascript I would use the second link on localStorage, the first is very good documentation about how to use it, and the third is the actual specification page for the feature.
Also, I included the code for setting cookies to be thorough, not because you really need it. localStorage is supported all the way back to IE8 and in all the other major browsers.
If you want to check the compatibility of any javascript/html5 feature I suggest here.
Good Luck!
Related
In my asp.net web application. I need to validate a textbox entry to avoid these special characters \/:*>"<>|.I planned to replace the character with empty string, and for that wrote a javascript function and addded the attribute to call the function from server side as below
txtProjectName.Attributes.Add("onkeyup", "ValiateSpecialCharacter()");
As of this every thing is fine and the function is called.while enter any character. The function is
function ValiateSpecialCharacter(){
var txt=document.getElementById("<%=txtProjectName.ClientID%>").value;
txt.replace(/[\\\/:*>"<>|]/g, '');
alert(txt);
document.getElementById("<%=txtProjectName.ClientID%>").value=txt;
}
I use a regular expression in the function to do this. But the test is not getting replaced as planned. Is there any mistake in this code.Also note that the alert is working.
Try to get the result in txt ie, get the value of replaced text inside your variable.
txt = txt.replace(/[\\\/:*>"<>|]/g, '');
In your query you getting previous value.Assign properly like this txt = txt.replace(/[\\\/:*>"<>|]/g, '');.It show the latest result in alert box.
function ValiateSpecialCharacter(){
var txt=document.getElementById("<%=txtProjectName.ClientID%>").value;
txt = txt.replace(/[\\\/:*>"<>|]/g, '');
alert(txt);
document.getElementById("<%=txtProjectName.ClientID%>").value=txt;
}
This is not what you asked, but seems like a strange way to go about your needs. Unless, I misunderstood the question. Since you are running ASP.NET on the server, why use JavaScript for server validation?
It usually does make sense to validate input on the client. For that, you need to hook an event like form submit to call the javascript function.
If you want to validate on the server, use something like, inside a function handling form submit:
Regex re = new Regex("^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\\.[a-zA-Z]{1,})+$");
if (!re.IsMatch (domain.Text)) {
warningLabel.Text = "Domain format is invalid!";
formError = true;
}
Obviously, you don't validate the domain so change the regex etc. No JavaScript is needed for server-side validation.
I have this form, an official form (a character sheet for use at an Organized Play Event for a role-playing game, if it matters to anyone), that someone kindly turned into a fillable PDF form. I asked a question earlier about checkboxes and auto-calcualtions, and got that to work...but now I need to account for another variable (situational doubling of the Proficiency Bonus) in some of my calculations. Unfortunately, this variable is not represented anywhere on this form, and I can't just add fields to the form (it being an official form, at least when printed). Without adding more fields to the (printed) form, how can I account for this additional variable?
I thought about just allowing the user to override the auto-calculation by typing in the field, but I can't figure out how to make that happen. Is this a good solution? Is this relatively simple to code?
If your answer involves adding code to my form, please include a code snippet I can modify, and a description of where I should insert it into my existing code, or if there is somewhere else I need to be adding it instead.
Code Sample:
//check bonus = stat bonus + applicable proficiency bonus
var profUse = this.getField("SklAcrProf").value;
var stat = Number(this.getField("DEX1").value);
var profVal = Number(this.getField("Proficiency Bonus").value);
var check = Number('-2');
if (profUse != "Off"){
check = stat + profVal;
}
else{
check = stat;
}
event.value = check;
If the form only needs to remain the same, when printed, the simplest solution may be to go ahead and add the fields that you need. You can set them up, so that they are "visible but doesn't print". This option can be selected in the Form Field drop-down list, in the Text Field Properties, General Tab, under Common Properties.
This way, you can still incorporate the data in your formulas, but it has no affect on the printed document.
So I've made this search that does what its supposed to do front-end wise. However, when submitting I'd like the query to ignore commas.
Right now I'm using commas to make a comma separated search. The whole thing is, when I submit; the comma's are included and thus messes up my search values.
Is there any way to ignore comma's upon submit?
Example: Searching [Example][Test] will actually return Example,Test.
I've made a fiddle here
Any suggestions and help is greatly appreciated.
var firster = true;
//capture form submit
$('form.nice').submit(function(e){
if(firster){
// if its the first submit prevent default
e.preventDefault();
// update input value to have no commas
var val = $('input').val();
val = val.replace(/,/g, ' ');
$('input').val(val);
// let submit go through and submit
firster = false;
$(this).submit();
}
});
DEMO
Looking at your profile, I'm guessing you're using python as a server-side language. The issue you're trying to solve is best dealt with server-side: never rely on front-end code to escape or format data that is being used in a query... check Bobby Tables for more info
Anyhow, in python, you could try this:
ajaxString.replace(",","\", \"")
Thiis will replace all commas witIh " OR ", so a string like some, keywords is translated into some", "keywords, just add some_field IN (" and the closing ") to form a valid query.
Alternatively, you can split the keywords, and deal with them separately (which could come in handy when sorting the results depending on how relevant the results might be.
searchTerms = ajaxString.split(",")
>>>['some','keywords']
That should help you on your way, I hope.
Lastly, I'd suggest just not bothering with developing your own search function at all. Just add a google search to your site, they're the experts. There is just no way you, by yourself, can do better. Or even if you could, just imagine how long it'd take you!
Yes, sometimes a company will create their own search-engine, but only if they have a good reason to do so, and have the resources such an endevour requires. Programming is often all about being "cleverly lazy": Don't reinvent the wheel.
So, I have some code that should do four things:
remove the ".mp4" extension from every title
change my video category
put the same description in all of the videos
put the same keywords in all of the videos
Note: All of this would be done on the YouTube upload page. I'm using Greasemonkey in Mozilla Firefox.
I wrote this, but my question is: how do I change the HTML title in the actual HTML page to the new title (which is a Javascript variable)?
This is my code:
function remove_mp4()
{
var title = document.getElementsByName("title").value;
var new_title = title.replace(title.match(".mp4"), "");
}
function add_description()
{
var description = document.getElementsByName("description").value;
var new_description = "Subscribe."
}
function add_keywords()
{
var keywords = document.getElementsByName("keywords").value;
var new_keywords = prompt("Enter keywords.", "");
}
function change_category()
{
var category = document.getElementsByName("category").value;
var new_category = "<option value="27">Education</option>"
}
remove_mp4();
add_description();
add_keywords();
change_category();
Note: If you see any mistakes in the JavaScript code, please let me know.
Note 2: If you wonder why I stored the current HTML values in variables, that's because I think I will have to use them in order to replace HTML values (I may be wrong).
A lot of things have been covered already, but still i would like to remind you that if you are looking for cross browser compatibility innerHTML won't be enough, as you may need innerText too or textContent to tackle some old versions of IE or even using some other way to modify the content of an element.
As a side note innerHTML is considered from a great majority of people as deprecated though some others still use it. (i'm not here to debate about is it good or not to use it but this is just a little remark for you to checkabout)
Regarding remarks, i would suggest minimizing the number of functions you create by creating some more generic versions for editing or adding purposes, eg you could do the following :
/*
* #param $affectedElements the collection of elements to be changed
* #param $attribute here means the attribute to be added to each of those elements
* #param $attributeValue the value of that attribute
*/
function add($affectedElements, $attribute, $attributeValue){
for(int i=0; i<$affectedElements.length; i++){
($affectedElements[i]).setAttribute($attribute, $attributeValue);
}
}
If you use a global function to do the work for you, not only your coce is gonna be easier to maintain but also you'll avoid fetching for elements in the DOM many many times, which will considerably make your script run faster. For example, in your previous code you fetch the DOM for a set of specific elements before you can add a value to them, in other words everytime your function is executed you'll have to go through the whole DOM to retrieve your elements, while if you just fetch your elements once then store in a var and just pass them to a function that's focusing on adding or changing only, you're clearly avoiding some repetitive tasks to be done.
Concerning the last function i think code is still incomplete, but i would suggest you use the built in methods for manipulating HTMLOption stuff, if i remember well, using plain JavaScript you'll find yourself typing this :
var category = document.getElem.... . options[put-index-here];
//JavaScript also lets you create <option> elements with the Option() constructor
Anyway, my point is that you would better use JavaScript's available methods to do the work instead of relying on innerHTML fpr anything you may need, i know innerHTML is the simplest and fastest way to get your work done, but if i can say it's like if you built a whole HTML page using and tags only instead of using various semantic tags that would help make everything clearer.
As a last point for future use, if you're interested by jQuery, this will give you a different way to manipulate your DOM through CSS selectors in a much more advanced way than plain JavaScript can do.
you can check out this link too :
replacement for innerHTML
I assume that your question is only about the title changing, and not about the rest; also, I assume you mean changing all elements in the document that have "title" as name attribute, and not the document title.
In that case, you could indeed use document.getElementsByName("title").
To handle the name="title" elements, you could do:
titleElems=document.getElementsByName("title");
for(i=0;i<titleElems.length;i++){
titleInner=titleElems[i].innerHTML;
titleElems[i].innerHTML=titleInner.replace(titleInner.match(".mp4"), "");
}
For the name="description" element, use this: (assuming there's only one name="description" element on the page, or you want the first one)
document.getElementsByName("description")[0].value="Subscribe.";
I wasn't really sure about the keywords (I haven't got a YouTube page in front of me right now), so this assumes it's a text field/area just like the description:
document.getElementsByName("keywords")[0].value=prompt("Please enter keywords:","");
Again, based on your question which just sets the .value of the category thingy:
document.getElementsByName("description")[0].value="<option value='27'>Education</option>";
At the last one, though, note that I changed the "27" into '27': you can't put double quotes inside a double-quoted string assuming they're handled just like any other character :)
Did this help a little more? :)
Sry, but your question is not quite clear. What exactly is your HTML title that you are referring to?
If it's an element that you wish to modify, use this :
element.setAttribute('title', 'new-title-here');
If you want to modify the window title (shown in the browser tab), you can do the following :
document.title = "the new title";
You've reading elements from .value property, so you should write back it too:
document.getElementsByName("title").value = new_title
If you are refering to changing text content in an element called title try using innerHTML
var title = document.getElementsByName("title").value;
document.getElementsByName("title").innerHTML = title.replace(title.match(".mp4"), "");
source: https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML
The <title> element is an invisible one, it is only displayed indirectly - in the window or tab title. This means that you want to change whatever is displayed in the window/tab title and not the HTML code itself. You can do this by changing the document.title property:
function remove_mp4()
{
document.title = document.title.replace(title.match(".mp4"), "");
}
Can anyone help me. I don't use Client-side Javascript often with HTML.
I would like to grab the current url (but only a specific directory) and place the results between a link.
So if the url is /fare/pass/index.html
I want the HTML to be pass
This is a quick and dirty way to do that:
//splits the document.location.href property into an array
var loc_array=document.location.href.split('/');
//have firebug? try a console.log(loc_array);
//this selects the next-to-last member of the array.
var directory=loc[loc.length-2]
url = window.location.href // Not particularly necessary, but may help your readability
url.match('/fare/(.*)/index.html')[1] // would return "pass"
There may be an easier answer, but the simplest thing I can think of is just to get the current URL with window.location and use some type of parsing to get which directory you are looking for.
Then, you can dynamically append the HTML to your page.
This may get you started:
var linkElement = document.getElementById("whatever");
linkElement.innerHTML = document.URL.replace(/^(?:https?:\/\/.*?)?\/.*?\/(.*?)\/.*?$/i,"$1");