comparing innerHTML value with a string variable in javascript - javascript

function Open() {
var cc = document.getElementById('FName');
if ('Newfile.rtf' == cc.innerHTML)
{
alert("New File");
} //close If NewFile.rtf
else {
alert("Not new file");
}
}//close Open()
Here I have string "NewFile.rtf" in a element with id="FName" on the page. When the FName contains "Newfile.rtf" in it it stills goes to the else part of the function instead of going to if part. I tried different ways to write the compare statement in the if condition, no luck . Appreciate the help if anyone can help figure out this.
Thank you.

The simplest explanation is that your cc.innerHTML call is not returning what you think it is returning. Why don't you console.log or debug.
add something like
var innerhtml = cc.innerHTML;
console.log("innerHTML = " + innerhtml) // wont work in IE.
before the if statement.

Try using regular expressions to find your filename, also check if the text you are searching is not into another DOM element, elimate left and right spaces, you should use Google Chrome for debuging the Javascript code:
var html = document.getElementById('FName').innerHTML;
if( html.search("Newfile.rtf") != -1) { /*found*/ }
else { /*not found*/ }

but what's the type of this element? if it's about an input text type .. you can't use innerHTML but you'll use value then.

Use innerText to get that
function Open() {
var cc = document.getElementById('FName');
if ('Newfile.rtf' == cc.innerText)
{
alert("New File");
} //close If NewFile.rtf
else {
//enter code here
alert("Not new file");
}
}

Related

How to match anything between < & > in regex?

I'm trying to match anything that lies between < and >, and nothing seems to be working.
My current code is:
var regex = /\<(.*?)\>/
var targeting = $('#auto-expand').val //A text area
function validateText(field)
{
if (regex.test(field) == true)
{
alert(field.match(regex))
}
else
{
alert("fail")
}
}
It keeps returning fail, not sure why.
Any help would be so great! :)
It's not clear from your question how you are calling the validateText function. But it looks like are trying to set targeting outside the function, which means you are probably setting it before there's text in the box.
Below I change val to val() to call the function and looked up the value when the function runs rather than before. The regex itself works fine (keeping this in mind)
var regex = /<(.*?)>/
function validateText() {
var targeting = $('#auto-expand').val() //A text area
if (regex.test(targeting) == true) {
alert(targeting.match(regex))
} else {
alert("fail")
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="auto-expand"></textarea>
<button onclick=validateText()>Test</button>

If/Else Conditional not running the second time I call the function

When I run the function the first time, either condition will work. But when I run the function a second time, the new value of "cute" will not change the background image.
$("#sbmt-button").click(newImage);
function newImage(){
event.preventDefault();
var cute = $("#cute").val();
$("#cute").val(" ");
if (cute == "kittens") {
$("body").attr("class", "kittens");
console.log(cute);
} else if (cute == "puppies"){
$("body").attr("class", "puppies");
console.log(cute);
}
}
http://codepen.io/ElaineM/pen/jbYbwj
Your code actually works, but only thing is you need to use $("#cute").val(""); instead of $("#cute").val(" ");, which puts a space and it doesn't match the values.
Also, you may try doing the comparison this way by trimming the empty spaces:
function newImage(){
event.preventDefault();
var cute = $("#cute").val().trim();
$("#cute").val(" ");
if (cute == "kittens") {
$("body").attr("class", "kittens");
console.log(cute);
} else if (cute == "puppies"){
$("body").attr("class", "puppies");
console.log(cute);
}
}
The line $("#cute").val(" "); puts a space in the text box. What you want is an empty string: $("#cute").val("");
Replacing it with an empty string seems to give you your desired output.
PROBLEM
You need to use event object e passed to event handler as an argument, otherwise your button acts as a submit button and the page gets refreshed.
SOLUTION
Use the following code instead:
function newImage(e){
e.preventDefault();
var cute = $("#cute").val();
console.log(cute);
if (cute === "kittens") {
$("body").attr("class", "kittens");
} else if (cute === "puppies"){
$("body").attr("class", "puppies");
}
// Reset input
$("#cute").val("");
}
EXAMPLE
See updated example for demonstration.

Setting DOM attributes with jQuery and getting through Javascript returns 'undefined'

That's not that great of a title for the question, so if anyone else has a better way to word it after reading it, that'd be appreciated.
Disclosure out of the way, this is homework. The assignment for this week is to refactor our already existing plain JS code to use JQM and I'm having an issue with a conversion I can't quite figure out, here's the code:
function populateItemLinks(key, listItem)
{
var ecLink = $('<a class="padRightRed"></a>');
ecLink.attr("href", "#");
ecLink.attr("key", key);
ecLink.html("Edit Character");
ecLink.on("click", editCharacter);
ecLink.appendTo(listItem);
console.log(ecLink.attr("key"));
ecLink = $('<a class="padLeftRed"></a>');
ecLink.attr("href", "#");
ecLink.attr("key", key);
ecLink.html("Delete Character");
ecLink.on("click", deleteCharacter);
ecLink.appendTo(listItem);
console.log(ecLink.attr("key"));
};
function deleteCharacter()
{
var toDelete = confirm("Do you wish to delete this character?");
if (toDelete)
{
console.log(this.key);
alert("Character was deleted.");
localStorage.removeItem(this.key);
$.mobile.changePage("#home");
}
else
{
alert("Character was not deleted.");
}
}
The issue is the using of the .key attribute as an itentified for the links in the populateItemLinks functions. When it was strait javascript, I could just do linkname.key = key; and then get the key back in the deleteCharacter function with "this.key". Well, now it's always returning undefined and I can't think of any way that wouldn't be convoluted to get the same functionality as the non-JQM version, so any help would be appreciated.
The reason your code is returning undefined is that you're trying to read a property of the DOM element, but you've set an attribute of the DOM element.
The top answers for this question explain the different between the two: .prop() vs .attr()
If you were to set the property of your newly created DOM element like this:
ecLink.prop('key', 12355);
And continued to directly access the DOM element (not via jQuery):
this.key; // 123455
All would of been well. Here is a JSFiddle example showing this in further detail.
Anyway, I've adjusted your code to work with the attribute you're setting:
function deleteCharacter()
{
var toDelete = confirm("Do you wish to delete this character?");
if (toDelete)
{
var key = $(this).attr('key');
alert("Character was deleted.");
localStorage.removeItem(key);
$.mobile.changePage("#home");
}
else
{
alert("Character was not deleted.");
}
}
Having said all this, Data attributes are better suited for storing arbitrary data against a DOM element:
ecLink.data('key', myKey); // set
ecLink.data('key'); // get
What I would do is pass the clicked ecLink as an argument to deleteCharacter() like this:
ecLink.on("click",function() { deleteCharacter($(this)); });
Then you can modify deleteCharacter():
function deleteCharacter(el)
{
var toDelete = confirm("Do you wish to delete this character?");
if (toDelete)
{
var key = el.attr('key'); //get the key attribute
console.log(key);
alert("Character was deleted.");
localStorage.removeItem(key);
$.mobile.changePage("#home");
}
else
{
alert("Character was not deleted.");
}
}

validating FCKeditor

how can FCKeditor be validated for required field using javascript.
Try this,
var EditorInstance = FCKeditorAPI.GetInstance('message') ;
if(EditorInstance.EditorDocument.body.innerText.length<=0)
{
alert("This firld is mandatory");
EditorInstance.EditorDocument.body.focus();
return false;
}
Source:
http://dreamtechworld.wordpress.com/2008/12/06/validating-firld-in-fckeditor-using-javascript/
Use FireBug, and see what hidden textarea it is updating. Then check that element.
if (document.getElementById('fckinstance').innerHTML === '') {
alert('required field');
}
That is just an example. It probably doesn't use an id like that either, because of multiple instances on the same page.
The textarea that FCKeditor replaces is probably the one that holds its HTML.
Note too, the FCKeditor can seem blank, even though there is HTML in it.
To Validate FCKeditor for being empty, create below function and call it whenever going to validate your editor containing TEXTAREA:
function FCKCopy() {
for (var i = 0; i < parent.frames.length; ++i ) {
if (parent.frames[i].FCK)
parent.frames[i].FCK.UpdateLinkedField();
}
}
Then add another function to Strip HTML tags from TEXTAREA's value:
function stripHTML(oldString) {
var matchTag = /<(?:.|\s)*?>/g;
return $.trim(oldString.replace(matchTag, ""));
}
In above function used jQuery's trim function. Use jQuery or replace it with some trimming function for java script such as:
function trimIt(text) {
rwhite = /\s/;
trimLeft = /^\s+/;
trimRight = /\s+$/;
if ( !rwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
return text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
}
Now you can check value of TEXTAREA for example as below:
if (stripHTML($('message').val()) == '') {
alert('Please enter Message.');
}
Hope it will work as good as worked for me.
Have fun
this may be useful for someone
var EditorInstance = FCKeditorAPI.GetInstance('JobShortDescription');
alert(EditorInstance.GetHTML());
resource is http://docs.cksource.com/FCKeditor_2.x/Developers_Guide/JavaScript_API

how to change textbox background color through javascript?

my javascript-
function validate_loginform(loginform)
{
var uid = loginform.uid.value;
var pass = loginform.pass.value;
if(uid == "")
{
color('uid');
return false;
}
if(pass == 0)
{
color('pass');
return false;
}
return true;
}
function color(traget)
{
var targetbox = document.getElementById(target);
targetbox.style.backgroundColor="red";
}
but background color is not getting changed even it is not returning fasle value. if I remove the color('uid'); nad put alert("user name required"); then this script is working fine.Whats wrong?
it backgroundColor in actual program I just missed it here only
With jQuery you could try this:
$("#textbox").css("background-color", "red");
dont call color function, change color inside if condition like-
if(uid == "")
{
//alert("You must enter User ID.","error");
loginform.uid.style.borderColor='red';
loginform.uid.focus();
return false;
}
Typo?
backgroungColor
^
Update
Typo?
function color(traget)
^^^^^^
{
var targetbox = document.getElementById(target);
Seriously, actual code does matter.
Beware your spelling. It should be "target", not "traget".
function color(traget)
You've spelt target wrong in your function header and background wrong in the last line of the function.
just remove the single quote (') from color('uid')
and write it as color(uid);

Categories