How to echo something from javascript to div class html - javascript

Javascript
function validateForm() {
var result;
var keywords = document.querySelectorAll('#keywords');
[].slice.call(websites).forEach(function(website) {
if (website.value == '') {
website.focus();
HERE I SAY SOMEHOW THE ERROR
result = false;
return true;
}
});
return result;
}
HTML
<div class="error-website">HERE THE ERROR IS GETTING ECHOED</div>
How do i echo website in that div above and how do i add the error in that if condition.

Try:
document.querySelectorAll('.error-website')[0].innerHTML = 'Website';
As NULL and VisioN has pointed , this:
document.querySelector('.error-website').innerHTML = 'Website';
is even faster , because of "querySelector is faster unless the match is the last DomNode in the DOM".

First of all, it would be more appropriate to use an ID not a class; the reason is that classes are meant for, well, classes (i.e. categories) of elements; however, in your case, you are dealing with one single unique element (you'll only have one), so assuming you take my advice and change to the following markup:
<div id="error-website">HERE THE ERROR IS GETTING ECHOED</div>
... it will be as simple as:
document.getElementById('error-website').innerHTML = "whatever <strong>you</strong> <em>like</em>";

$(".error-website").text("Website")

document.getElementById('error-website').innerHTML = ....
if you use an id...

Use DOM document.getElementsByClassName
Eg.
function validateForm() {
var result;
var keywords = document.querySelectorAll('#keywords');
[].slice.call(websites).forEach(function(website) {
if (website.value == '') {
website.focus();
HERE I SAY SOMEHOW THE ERROR
result = false;
return true;
}
});
return result;
var a=validateForm();
if(a){
document.getElementsByClassName("error-website")[0].innerHTML=a;
}
NOTE: getElementsByClassName() does not work in Internet Explorer 5,6,7, and 8

Related

String literal not being appended to DOM

I'm trying to make functions that return me an HTML element as a string so I can eventually append them to the DOM and pass them around my functions. I have paragraph, heading, and div's working but cannot for the life of me seem to get links to work.
This is the non-working codepen
The javascript in question is:
function link(href,text,css){
let target = ``;
if(css == null ){
return target;
}
return addStyles(target,css);
}
My addStyles function is:
function addStyles(target,css){
if(css == null ){
return target;
}
let props = Object.keys(css);
props.forEach((prop)=>{
switch(prop){
case 'id':
$(target).attr('id', css[prop]);
break;
case 'class':
let classes = css[prop];
if(Array.isArray(css[prop])){
classes = css[prop].toString().replace(',', ' ');
}
$(target).addClass(classes);
break;
default:
$(target).attr('data-name', 'Timi');
}
});
return target;
}
which for a long time gave me errors but only when calling it from the link function. I tried hard-coding in the href to see if maybe my string literals were giving me the errors but still no avail.
while calling it from this function it works perfectly
function createDiv(css){
let newDiv = $(div);
return addStyles(newDiv,css);
}
I say that the addStyles function works and that I think it's the link() that is giving me problems because createDiv works and appends the DOM with these calls
app.append(createDiv({id: 'testing'}));
app.append(createDiv({class: ['bar', 'snuff']}));
app.append(createDiv()).append(createDiv({class: 'timi'})).append(paragraph('Hey guys!'));
$('#testing').append(heading(1,'Hello'));
your let target = ; is a string. you should use a DOM and manipulate its attribute instead
function link(href,text,css){
let target = document.createElement('a');
let linkText = document.createTextNode(text);
target.appendChild(linkText);
target.href = href;
if(css == null ){
return target;
}
return addStyles(target,css);
}
You forgot to wrap the a tag with bling:
let target = $(``);
The reason your createDiv function is working as expected and your link function isn't is because you haven't wrapped your representation of an html element (the one you pass to addStyles) in a jQuery wrapper like you do in your createDiv function. See my below code for what I've changed to get it to work:
function link(href,text,css){
let target = `${text}`;
if(css == null ){
return target;
}
return addStyles($(target)[0],css);
}
codepen
I'm a little lost actually why we need to add [0] to $(target) but we do. Maybe someone else could chime in about why that is the case with ${text} and not with <div></div>
Edit: disregard above about the [0] and see comments on this answer.

my chain as jQuery

The code:
<body>
<div class="class0"> link </div>
<div class="class0"></div>
<div class="class0"></div>
</body>
<script>
proto={};
$ = function(selector){
var tags = document.querySelectorAll(selector);
tags.__proto__ = proto;
return tags;
}
proto.addClass = function(className){
for (var i = 0; i < this.length; i++){
this[i].classList.add(className);
}
return this;
}
proto.html = function(){
return this[0].innerHTML;
}
</script>
console.log( $('div').addClass('class1').html() ); this works
console.log( $('div').addClass('class1').html().addClass('class 2').html() ); but this not - need this to work
html(), on the one hand, should return this[0].innerHTML, on the other hand should return this.
I do not know how to combine it.
html should return this in case if it's a setter function (you don't have this yet):
$('div').addClass('class1').html('<span>HTML</span>').addClass('class 2');
In your case html is a getter function so it must return HTML string for the first element in collection. Hence there is no way you can combine both styles.
What you are trying to do is not possible, a function can return only one value.
If you have a look at the jQuery fluent API also, the you can't do what you are trying to do with the getter version of .html()
The getter & setter version can go something like
proto.html = function (html) {
if (arguments.length == 0) {
return this[0].innerHTML;
}
this[0].innerHTML = html;
return this;
}
proto.html = function(str){
if(str == undefined){
// getter mode
return this[0].innerHTML;
} else {
// setter mode
this[0].innrHTML = str;
return this;
}
}
Usage
$('div').html() // works as getter
$('div').html('some html').foo(); // works as setter
The task hasn't decided yet.
The comment of author of the question (team leader at EPAM systems):
"Need to redefine this's toString inside methods.
Now if you use the result as a string it will remain as string although you will
return this"
The decision exists

What is failing in my form validation function?

So I've tried making a function that loops through the elements of a form and checks the length of the elements, and if so, change the class so they can be styled differently. The code I have I assumed would work, and I'm not getting any errors in my console, so I can't pinpoint what is going wrong exactly. If someone could tell me why this won't work or how to fix it that would be awesome! Thankyou!
function validate_form(){
var form = document.forms['form_name']; //store form into a variable
var validated = true; // store return value for onsubmit attribute
for(i=0; i<form.elements.length; i++){
if(form.elements[i].value.length){ // check if form elements are empty
form.elements[i].className = "validate_failed"; // if elements are empty, add a class that will style them
validated = false;
return validated;
} else{
validated = true;
return validated;
}
return validated;
}
return validated;
}
Try
function validate_form(){
var form = document.forms['form_name']; //store form into a variable
for(var i=0; i<form.elements.length; i++){
if(form.elements[i].value.length===0){ // check if form elements are empty
form.elements[i].className = "validate_failed"; // if elements are empty, add a class that will style them
return false;
}
return true;
}
assuming
<form onsubmit="return validate_form()" ...
or make it all unobtrusive
window.onload=function() {
document.forms['form_name'].onsubmit=function() {
for(var i=0; i<this.elements.length; i++){
this.elements[i].className = "";
if(this.elements[i].value.length===0){ // check if form elements are empty
this.elements[i].className = "validate_failed"; // if elements are empty, add a class that will style them
return false;
}
return true;
}
}
}
Because your are returning validated during the first run through of the loop, you'll only ever check the first element of the form. You'll just want to set validated, and return it after the loop (or return when you first set it to false, depending on what you want to do).
Also, like Joe commented, you should have var i instead of just i so that i is not global.
Following code will work for empty element
if(!form.elements[i].value.length){
OR
if(form.elements[i].value.length === 0){

Can I reduce this Javascript code?

Can I reduce
function n()
{
var a;
if(a = document.getElementById('fb0'))
{
a.onclick = i0;
document.getElementById('fb1').onclick = i1;
}
}
to
function n()
{
if(document.getElementById('fb0').onclick = i0)
{
document.getElementById('fb1').onclick = i1;
}
}
I don't have a debugger right now. I know that document.getElementById('fb0') returns a value because the first snippet works fine. But does it need the assignment to be evaluated in the if statement?
No, you can't.
document.getElementById('fb0'), as the function name already says, returns the html element with has the id equal to fb0. After that you are accessing the attribute onclick. But it the get fails it will break the script.
On the first scenario you test if the assignment works, if does it means the element exists and will only execute if it exists.
Those are different behaviors.
Not really; if getElementById('fb0') doesn't return anything your page will get an error, and in the first case it wouldn't.
To check if "document.getElementById('fb0')" returns an element or null, the second version don't do it and an error will be throw if there is no element with id "fb0". The second version is ok if you don't remove the "fb0" element from the DOM at some point.
That would fail if document.getElementById('fb0') were not to exist. document.getElementById('fb0').onclick wouldn't mean much in that case.
If you do a lot of DOM selection by ID, make a shortened version of that method:
function byId( id ) { return document.getElementById(id); };
function n() {
var a;
if(a = byId('fb0')) {
a.onclick = i0;
byId('fb1').onclick = i1;
}
}
In this case, doing the assignment inside the condition doesn't save you any characters. It's the same length to do it with the declaration.
function byId( id ) { return document.getElementById(id); };
function n() {
var a = byId('fb0');
if(a) {
a.onclick = i0;
byId('fb1').onclick = i1;
}
}

How to find input element id by value?

How do I get the id of an input element based on its value? The values will always be unique and there are only seven of them. I have tried this:
$('#wrapper').find("input[value='"+value+"']").each(function(){
return this.id;
});
But nothing is returned!
Try
$(this).id nope, this.id works, no need to create a jQuery object for the ID.
or
$(this).attr('id')
HTH
EDIT:
This might work:
$('#wrapper').find("input[value='"+value+"']").attr('id');
You write return this.id;… Return where? You simply return value from anonymous functions and I don't see where you ever trying to use it. So the answer is:
var idYouAreSearchingFor = $('#wrapper').find("input[value='"+value+"']").attr('id');
your code is almost good:
$('#wrapper').find("input[value='"+value+"']").each(function(){
return $(this).attr("id")
});
check here
http://jsfiddle.net/5xsZt/
edit: i have just tested it with this.id it works to. Your code is right. Your error is somewhere else: check it:
http://jsfiddle.net/5xsZt/3/
You can solve this using a filter. Like this:
$('#wrapper input').filter(function() {
return $(this).val() == value;
}).each(function() {
return this.id;
});
Here's a version that will definitely work in all mainstream browsers:
function getInputWithValue(wrapper, value) {
var inputs = wrapper.getElementsByTagName("input");
var i = inputs.length;
while (i--) {
if (inputs[i].value === value) {
return inputs[i];
}
}
return null;
}
var wrapper = document.getElementById("wrapper");
var input = getInputWithValue(wrapper, "some value");
window.alert(input.id);

Categories

Resources