I am new to jQuery and I can't see where my code is wrong. I am trying to get an element with the id of custom-logo-video to change its innerHTML with an if statement (if it is "" or blank etc). However it is not working. What am I doing wrong?
$(document).ready(function(){
var a = $("#custom-logo-video");
if (!a.trim()) {
// is empty or whitespace
a.innerHTML("easy");
} else {
a.innerHTML("hard");
}
});
you can try:
$(document).ready(function () {
var a = $('#custom-logo-video').html();
if (!$.trim(a)) {
// is empty or whitespace
$('#custom-logo-video').html("easy");
} else {
$('#custom-logo-video').html("hard");
}
});
A few issues with the code
var a = $(#custom-logo-video);
selection requires quotes around it
var a = $('#custom-logo-video');
When you use jquery to select, you have a jQuery object so innerHTML won't work, you want to use either .html() or .text() to get the inner text. Here is how I fixed it.
$(document).ready(function(){
var a = $('#custom-logo-video');
if (!a.html()) {
// is empty or whitespace
a.html("easy");
}else{
a.html("hard");
}
});
You can read more here: https://learn.jquery.com/using-jquery-core/selecting-elements/
You're using innerHTML which isn't necessary since you're using jQuery. .html() will suffice.
Try this:
$(document).ready(function(){
var a = $("#custom-logo-video");
if ( !a.html().trim() ) {
// is empty or whitespace
a.html('easy');
}
else {
a.html('hard');
}
});
EDIT: fixed typos and logic in code.
Try this as well,
$(document).ready(function () {
var a = $('#custom-logo-video').html();
(a !== null && a.trim().length > 0) ? a.html('hard') : a.html('easy');
});
Try this:
$(document).ready(function(){
var a = $('#custom-logo-video');
if (!a.trim()) {
// is empty or whitespace
a.text("easy");
} else {
a.text("hard");
}
});
Try this code:
$(document).ready(function(){
var a = $("#custom-logo-video");
// To check if the node is empty or not I am
// calling jQuery api is(':empty')
if (a.is(':empty')) {
// is empty or whitespace
// To replace the innerHTML of a node you call a .html() jQuery api
a.html("easy");
} else {
a.html("hard");
}
});
Working Example
Related
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>
I have the following JQuery code I am working on. When I test it, the expected values are shown in the span but not in the input text box.
JQ
$(function() {
$("#textbox").each(function() {
var input = '#' + this.id;
counter(input);
$(this).keyup(function() {
counter(input);
});
});
});
function counter(field) {
var number = 0;
var text = $(field).val();
var word = $(field).val().split(/[ \n\r]/);
words = word.filter(function(word) {
return word.length > 0 && word.match(/^[A-Za-z0-9]/);
}).length;
$('.wordCount').text(words);
$('#sentencecount').text(words);
}
Please see Fiddle. Please let me know where I have gone wrong. Still new to JS.
Thanks
Change this:
$('#sentencecount').text(words);
to this:
$('#sentencecount').val(words);
The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method. -> http://api.jquery.com/text/
Trying using val() instead This should fix it up.
http://jsfiddle.net/josephs8/6B9Ga/8/
You can not set text to an input you must use value
try this.
$('#sentencecount').text(words);
//has to be
$('#sentencecount').val(words);
and i have also updated your Jsfiddle
$(function() {
$("#textbox").each(function() {
var input = '#' + this.id;
counter(input);
$(this).keyup(function() {
counter(input);
});
});
});
function counter(field) {
var number = 0;
var text = $(field).val();
var word = $(field).val().split(/[ \n\r]/);
words = word.filter(function(word) {
return word.length > 0 && word.match(/^[A-Za-z0-9]/);
}).length;
$('.wordCount').text(words);
$('#sentencecount').val(words);
}
I have the following structure:
<div id="campaignTags">
<div class="tags">Tag 1</div>
<div class="tags">Tag 2</div>
<div class="tags">Tag 3</div>
</div>
And I'm trying to match user input against the innerText of each children of #campaignTags
This is my latest attempt to match the nodes with user input jQuery code:
var value = "Tag 1";
$('#campaignTags').children().each(function(){
var $this = $(this);
if(value == $(this).context.innerText){
return;
}
The variable value is for demonstration purposes only.
A little bit more of context:
Each div.tags is added dynamically to div#campaignTags but I want to avoid duplicate values. In other words, if a user attempts to insert "Tag 1" once again, the function will exit.
Any help pointing to the right direction will be greatly appreciated!
EDIT
Here's a fiddle that I just created:
http://jsfiddle.net/TBzKf/2/
The lines related to this question are 153 - 155
I tried all the solutions, but the tag is still inserted, I guess it is because the return statement is just returning the latest function and the wrapper function.
Is there any way to work around this?
How about this:
var $taggedChild = $('#campaignTags').children().filter(function() {
return $(this).text() === value;
});
Here's a little demo, illustrating this approach in action:
But perhaps I'd use here an alternative approach, storing the tags within JS itself, and updating this hash when necessary. Something like this:
var $container = $('#campaignTags'),
$template = $('<div class="tags">'),
tagsUsed = {};
$.each($container.children(), function(_, el) {
tagsUsed[el.innerText || el.textContent] = true;
});
$('#tag').keyup(function(e) {
if (e.which === 13) {
var tag = $.trim(this.value);
if (! tagsUsed[tag]) {
$template.clone().text(tag).appendTo($container);
tagsUsed[tag] = true;
}
}
});
I used $.trim here for preprocessing the value, to prevent adding such tags as 'Tag 3 ', ' Tag 3' etc. With direct comparison ( === ) they would pass.
Demo.
I'd suggest:
$('#addTag').keyup(function (e) {
if (e.which === 13) {
var v = this.value,
exists = $('#campaignTags').children().filter(function () {
return $(this).text() === v;
}).length;
if (!exists) {
$('<div />', {
'class': 'tags',
'text': v
}).appendTo('#campaignTags');
}
}
});
JS Fiddle demo.
This is based on a number of assumptions, obviously:
You want to add unique new tags,
You want the user to enter the new tag in an input, and add on pressing enter
References:
appendTo().
filter().
keyup().
var value = "Tag 1";
$('#campaignTags').find('div.tags').each(function(){
if(value == $(this).text()){
alert('Please type something else');
}
});
you can user either .innerHTML or .text()
if(value === this.innerHTML){ // Pure JS
return;
}
OR
if(value === $this.text()){ // jQuery
return;
}
Not sure if it was a typo, but you were missing a close } and ). Use the jquery .text() method instead of innerText perhaps?
var value = "Tag 1";
$('#campaignTags').find(".tags").each(function(){
var content = $(this).text();
if(value === content){
return;
}
})
Here you go try this: Demo http://jsfiddle.net/3haLP/
Since most of the post above comes out with something here is another take on the solution :)
Also from my old answer: jquery - get text for element without children text
Hope it fits the need ':)' and add that justext function in your main customised Jquery lib
Code
jQuery.fn.justtext = function () {
return $(this).clone()
.children()
.remove()
.end()
.text();
};
$(document).ready(function () {
var value = "Tag 1";
$('#campaignTags').children().each(function () {
var $this = $(this);
if (value == $(this).justtext()) {
alert('Yep yo, return');)
return;
}
});
//
});
In my below jQuery code, I can't get correct length of inputString element, element's length changing on lookup function and I can't use global variable.
$('#ckekeKala').live("click" ,function(){
var len=$('#inputString').text().length;
alert(len);
});
function lookup(inputString) {
if(inputString.length != 0) {
$('[id^="lbl"]').attr("disabled", true);
}
});
}
} // lookup
HTML code:
<input style='width: 128px;' name='nameKala' id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
Extra braces in lookup function
function lookup(inputString) {
if(inputString.length != 0) {
$('[id^="lbl"]').attr("disabled", true);
}
}); <--- Remove this
} <--- Remove this
} // lookup
Just a thought, you could really easy this whole process up like so:
HTML
<input id="inputString" name="nameKala" type="text" style="width:128px" />
Script
// keep in mind, that depending on ur use and jQuery version, .live can be replaced with .bind or .on
$("#inputString").live("keyup", function(e) {
if ($(this).length > 0) {
$('[id^="lbl"]').attr("disabled", true);
};
})
.live("blur", function(e) {
// do fill work
});
$('#ckekeKala').live("click" ,function(){
var len=$('#inputString').val().length;
alert(len);
});
Example
Beside any syntax error that you can see in other answer and post. It would have been easy if you have put more code. But assuming that all other code that you haven't mention are correct and fixing this syntax error of
});
I think your lookup does not have access outside jQuery block. so what you can do is change it to make like this
lookup = function(inputString) {
if (inputString.length != 0) {
$('[id^="lbl"]').attr("disabled", true);
}
}
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