JavaScript add an HTML class to div. If statement. Bootstrap - javascript

You may have seen the input box with success tick glythicon.
I'm trying to make a form where the input box is normal (not green and no tick showing) and upon successful validation in JavaScript, I want it to change to to the green border and display the glythicon tick. I think that adding the class is the way to do it and I can't quite get it working.
I tried to use the following for adding a class:
document.getElementById('id').className.add('addditional classes');
But I can't figure out the correct syntax to get this code to work.
function validateName() {
var name = document.getElementById("first_name").value;
if(name.match(/^[A-Za-z]*\s{0}$/)){
document.getElementById('firstcheck').classform-group, has-feedback.add(' has-success');
document.getElementById('firstcheck2').classglythicon, glythicon-ok.add(' form-control-feedback');
}
HTML code
<div id="firstcheck" class="form-group has-feedback">
<input onblur="validateName()" id="first_name" type="text" class="form-control" id="inputSuccess2" aria-describedby="inputSuccess2Status">
<span id="firstcheck2" class="glyphicon glythicon-ok" aria-hidden="true"></span>
</div>
Any help would be appreciated!!!

Please always check your code carefully after copy+paste.
The placement of quotation marks is important, as is placement of dots
And this is jquery code:
$('id').addClass('addditional classes');
Try this instead:
function validateName() {
var name = document.getElementById("first_name").value;
if(name.match(/^[A-Za-z]*\s{0}$/)){
document.getElementById('firstcheck').className += 'form-group has-feedback has-success';
document.getElementById('firstcheck2').className += 'glythicon glythicon-ok form-control-feedback';
}
Also dont include , in the classnames string

Try to add the class this way:
//first get the element
var elem = document.getElementById("id");
//append new classes to your existing class
elem.className = elem.className + " additional classes";
//apply the same login in your remaining code
if(name.match(/^[A-Za-z]*\s{0}$/)){
elem = document.getElementById('firstcheck');
elem.className = elem.className + " has-success";
elem = document.getElementById('firstcheck2');
elem.className = elem.className + " form-control-feedback";
}
OR
You can easily achieve this with jquery like this:
$('id').addClass('additional-classes');

Since Bootstrap's JS needs jQuery you can make your life a bit easer here. I've created a small example https://jsfiddle.net/eg8dsgh2/. Just use jQuery's addClass()
Hope it helps

document.getElementById('firstcheck').classform-group, has-feedback.add(' has-success');
Is this invented? Where do you see something like this'
To add a class use className.
document.querySelector('#firstcheck').className += " has-success";

Related

Using regex with javascript on nodejs find html attribute and prepend something to its value

I have some markup in JS as follows:
<div class="col-sm-4">
<span id="some-media" class="media">Text</span>
</div>
I would like to select the class attribute of the span and prepend its value with lets say the characters: "::". So after the regex replace i would end up with:
<div class="col-sm-4">
<span id="some-media" class="::media">Text</span>
</div>
EDIT: Note that the order of the attributes in the HTML element is variable so my span attributes could very well have different order like so:
<div class="col-sm-4">
<span class="::media" id="some-media" >Text</span>
</div>
You got a regex solution, this is a DOMmy one:
var html = `<div class="col-sm-4">
<span id="some-media" class="media">Text</span>
</div>`
var doc = (new DOMParser()).parseFromString(html, "text/html");
var el = doc.getElementsByTagName('span')[0];
el.setAttribute('class', '::' + el.className);
console.log(
doc.getElementsByClassName('::media').length > 0 // check if modification's done
);
Since you have no way except Regular Expressions this can be considered as a workaround:
(<span[^>]*class=.)([^'"]+)
JS:
var html = `<div class="col-sm-4">
<span id="some-media" class="media">Text</span>
</div>
<span class="media" id="some-media">Text</span>
`;
console.log(
html.replace(/(<span[^>]*class=.)([^'"]+)/g, `$1::$2`)
);
This isn't using regex, but you can do it like this in vanilla JavaScript:
const el = document.getElementsByClassName('media')[0];
el.className = '::' + el.className;
Or in jQuery:
const $el = $('div span.media');
$el.attr('class', '::' + $el.attr('class'));
Hope this helps.
Don't parse html with regex, use DocumentFragment (or DOMParser) object instead:
var html_str = '<div class="col-sm-4"><span class="media">Text</span></div>',
df = document.createRange().createContextualFragment(html_str),
span = df.querySelector('span');
span.setAttribute('class', '::' + span.getAttribute('class'));
console.log(df.querySelector('div').outerHTML);
I think this is what you're after:
var test = $("#some-media")[0].outerHTML();
var test2 = '<div id="some-media" class="media">Text</div>'
if(/span/.test(test)) //Valid as contains 'span'
alert(test.replace(/(class=")/g, "$1::"));
if(/span/.test(test2)) //Not valid
alert(test.replace(/(class=")/g, "$1::"));
Since the order differs, writing a regex that captures all possible combinations of syntax might be rather difficult.
So we'd need a full list of rules the span follows so we can identify that span?
Got some more info about if the span occurs in a longer HTML string? Or is the string this span and this span only?
An alternative would be to use one of the several node DOM modules available, so you can work with HTML nodes and be able to use any of the above solutions to make the problem simpler.
But since you're using node:
1) Are you using any templating engines? If so, why not rerender the entire template?
2) Why does the class name have to change on the server side? Isn't there a workaround on the clientside where you do have access to the DOM natively? Or if it's just to add styling, why not add another css file that overwrites the styling of spans with className 'media'?
3) If all of the above is not applicable and it;s a trivial problem like you say, what error di you get using a simple replace?
strHTML.replace( 'class="media"', 'class="::media"' )
or if it has to be regex:
strHTML.replace( /class=\"(.*)\"/, 'class=\"::$1\"' );

Add class to dynamically created HTML node

I thought this was going to be a bit easier to do, but I have spent a good 2 hours on it, without being able to figure it out.
I have this output:
<div class="cart-contents">
Your shopping cart is empty
</div>
and I am dynamically creating about 5 spans with JS:
function outputValue(value){
//output.innerHTML = output.innerHTML + value;
output.innerHTML += "<br>" + "<span>" + value + "</span>";
}
so my last span div is a total. I created a CSS class of .total to change a few styles, I tried few things like output.classList.addClass(.total);
How can I dynamically add a class to just the last span?
this would be my output:
var output = document.querySelector(".cart-contents");
var total;
function outputValue(value){
//output.innerHTML = output.innerHTML + value;
output.innerHTML += "<br>" + "<span>" + value + "</span>";
}
<div class="cart-contents">
Your shopping cart is empty
//<span>would go here</span>
//<span>would go here</span>
//<span>would go here</span>
//<span>would go here</span>
//<span class="total">would go here</span>
</div>
To target the last span and add the class with javascript, you'd use a selector, like span:last-child, that gets the last span inside output, and then you'd use classList.add().
There is no addClass(), that's a jQuery method.
output.querySelector('span:last-child').classList.add('total')
FIDDLE
Not a fix for the problem, but this removes the problem:
You can do this in pure CSS, using the last-of-type selector. This is the best solution IMHO.
https://developer.mozilla.org/nl/docs/Web/CSS/:last-of-type
https://developer.mozilla.org/en-US/docs/Web/CSS/%3Alast-child
Codepen example: http://codepen.io/anon/pen/gMOXqK
Since this doesn't even need JavaScript, and only uses CSS without complicated selectors, this seems like the best solution.
Possible fixes for your problem:
Your addClassList syntax is incorrect.
See: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
output.classList.add("total");
This is the correct addClass syntax.
Is there any reason why you would add the class with JavaScript, instead of adding it instantly? If you would pass an (optional) class parameter, you could pass the class when adding the totals (assuming you know when you're adding the totals).
function outputValue(value){
outputValue(value,"");
}
function outputValue(value, class){
output.innerHTML += "<br>" + "<span class='" + class + "'>" + value + "</span>";
}

Get the value of an <input type="text"> that was created dynamically inside a modal

i would like to get the value of an <input type="text"> that was created dynamically inside a modal and put it into variable "newcomment".
This is how i make the input:
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text'id='comment_text' value='Comment'"+"onblur=newcomment=$('#comment_text').val()"+" onfocus=if(this.value==this.defaultValue)this.value=''>"+"</input>");
$("div.modal-body").append(p);
The problem is when i write something like "ok" inside the textbox in the modal, and after i focusout from the textbox: newcomment seems not update to "ok" and still have the default "Comment" value.
1st: You need to use newcomment=this.value instead of newcomment=$('#comment_text').val()
2nd: No need to add + signs in your input html code while you not trying to concatenate string by putting variables to it
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text' id='comment_text' value='Comment' onblur='newcomment=this.value; alert(newcomment);' onfocus=if(this.value==this.defaultValue)this.value='' />");
$("body").append(p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Not really the answer here, but might help you get at the root of the problem.
JS:
var newComment, defaultValue;
function doOnBlur(){
newComment = $('#comment_text').val()
}
function doOnFocus(){
if($('#comment_text').val() == defaultValue){
$('#comment_text').val('')
}
}
HTML:
<input type='text' id='comment_text' placeholder='Comment' onblur='doOnBlur()' onfocus='doOnFocus()' />
<!-- inputs dont have a close tag, also should use placeholder for temporary text -->
from here, you can set breakpoints in the debugger and see where your code is going wrong. You can also modify the functions much more easily rather than writing the executing code in the HTML

jQuery selector by form index and input name

Take the following page with two forms with different classes but each form has an input with the same name.
<form class='first_form'>
<input name='test' value='1' />
</form>
<form class='second_form'>
<input name='test' value='3'/>
</form>
I can get the form index and I know the name of the input but I do not know the index of the input.
Is there a way to chain a selector with the form index and the input name to get the value?
I have tried chaining but nothing seems to work
var inputName = 'test';
Var formIndex = 1;
$('*[name="' + inputName + '"]' +' ' + '$("form").eq(' + formIndex + ')').val();
FIDDLE
var formIndex=0;
var inputName="txtbox";
vall= $("form:eq("+ formIndex+") input[name= "+ inputName +" ]").val();
alert(vall);
your order was wrong
Untested, but could you do:
$('form:nth-of-type(1) input[name="test"]').val();
$("form:nth-child("+formIndex+") input[name='"+inputName+"']").val();
You could do in a more clever way:
var fieldName = 'test';
var formId = '.first_form'
$('form'+formId+' input[name='+fieldName+']).val()
Instead of index, use named selectors, like id or class. It will help you in the future find the correct form (when you will have more than 5, it will be hard to count witch one you are looking at :) )
But that is too complex:)
I would propose something like this:
var currentForm = $('form'+formId);
currentForm//here you can put a log into console if element has not been found and find that bug sooner.
currentForm.find('input[name='+fieldName+']').val()
You can access the form's element directly within the DOM using either of:
document.forms[formIndex]
document.forms[formName]
You can then reference an input element by name using:
document.forms[formIndex][inputName]
document.forms[formName][inputName]
Then just wrap it in $(...) to get yourself a jQuery collection. In your case:
var inputName = 'test',
formIndex = 1;
$(document.forms[formIndex][inputName]);
I imagine this is by far the most performant way, and it's readable too.
To add a little detail, document.forms is an HTMLCollection of all HTMLFormElements within a document. And given any HTMLCollection or HTMLFormElement you can access named elements within them as properties.

Add div below particular div using Javascript

I have some class name fawas that displays some content. Actually i have to add some content below the Div in java script.please help me.
<div class="fawas">
this is my name fawas khan.
</div>
my javascript code is
var dynamic = "this is my contact number.";
var _body = document.getElementsByTagName('body') [0].innerHTML
=dynamic;
what i'm getting is only a appended div.
In pure javaScript, getting an element by className is ugly. See How to Get Element By Class in JavaScript? for more information.
Basically, you'll want this function:
function getElementsByClass(tagType, className) {
var elems = document.getElementsByTagName(tagType);
var returns = [];
for (var i in elems) {
if ((' ' + elems[i].className + ' ').indexOf(' ' + className + ' ') > -1) {
returns.push(elems[i]);
}
}
return returns;
}
Once you have that, the rest is not too bad:
var dynamic = document.createElement("div");
dynamic.innerHTML = "this is my contact number.";
var elements = getElementsByClass("div", "fawas");
if (elements.length > 0) {
// just change the first, as you did in your post
elements[0].parentNode.insertBefore(dynamic, elements[0].nextSibling);
}
I dynamically create your new div, rather than just a text string.
Then, I get the parent of the element you want to insert after, use the insertBefore function on whatever is after the element of your choice.
Here is a working fiddle.
As others have shown you, this can be a lot cleaner using jQuery. I don't know enough node.js to know if it has functions that will be more convenient, so I gave a pure JS solution.
In case you're interested in jQuery solution, here's a Fiddle
<div class="fawas">
this is my name fawas khan.
</div>
$(function(){
var dynamic = ('this is my contact number.');
$('.fawas').after('<div class="fawas2">'+dynamic+'</div>');
});
Your html should be,
<div class="fawas">
this is my name fawas khan.
</div>
<div id="fawas-2">
</div>
Your script should be,
<script type="text/javascript">
var dynamic = "this is my contact number.";
document.getElementById('fawas-2').innerHTML =dynamic;
</script>
You can do this
var oldcontent = document.getElementsByTagName('body') [0].innerHTML;
document.getElementsByTagName('body') [0].innerHTML = oldcontent + dynamic
Where dynamic is the content you want to add

Categories

Resources