Reset before adding element and class - javascript

I've been trying to reset after inserting an element with a class with no success. Tried also innerHTML="" but it is not working.
Maybe because I'm using insertAdjacentHTML(). - ? I couldn't find a remove method before inserting.
let small = document.querySelector("small")
let img_1 = document.querySelector('[name="img_1"]')
//Image fields validation
if (img_1.value =="") {
img_1.classList.add('is-invalid_create')
small = '<small class="text-danger__Create">Campo imagen 1 no puede estar vacĂ­o</small>'
img_1.insertAdjacentHTML("afterend", small);
} else {
img_1.classList.add('is-valid_create')
img_1.classList.remove('is-invalid_create')
}
I'm trying to build a validation with an error message if fields are . I used insertAdjacentHTML because innerHTML was not showing the text.
fiddle : https://jsfiddle.net/gzsudqvm/
I tried to do a simpler approach like:
function setErrorFor(input, message) {
input.innerHTML = ""
input.classList.add('is-invalid_create')
input.innerHTML = "<small class='danger'>"+message+"</small>"
}
But the message is not rendering, and there are no errors.

It's hard to tell without seeing more of your code - without understanding just how/what you are trying to reset.
tried also innerHTML=""
For which element? If it was something like img_1.innerHTML="", then your small gets left behind because you added it outside img_1 . (If that's intentional/necessary then you could try something like el.parentElement.removeChild(el) to remove the left-over elements separately.)
used insertAdjacentHTML because innerHTML was not showing the text
Does the debugger show any errors? When you inspect the outer element, has it not been added to html at all, or is the text just not rendering?
EDIT: now that I can see the fiddle, I realize the field you're trying to reset is an input type, so you can't change innerHTML - you have to work with value and placeholder and maybe even defaultValue when setting/resetting.
I would suggest just resetting value and showing the message by adding a class with [::after][1] css, but you could also show it by setting a new placeholder or even value [I don't thing setting the error message as value is a good idea at all though]. You can define the placeholder style in css as ::placeholder; but personally, I much prefer the ::after approach.

Related

How to get html element after append with pure JavaScript?

I found some JQuery solutions, but I am limited by school task restrictions to use pure Javascript, and I need to use specific early appended element that is still not in DOM for replacing by my CKEDITOR.
Code:
function newOption(){
...
mainUL = document.getElementById("myUL");
var inputA = document.createElement("input");
inputA.type ="text";
inputA.style = "margin-right: 45px";
inputA.name = "option[]";
inputA.id = inputID;
mainUL.appendChild(inputA );
CKEDITOR.replace(inputID).setData('Type anything you want ...');
...
}
By replacing my input with CKEDITOR will JS fail, because input, commonly, is still not in DOM. I tried to use
mainUL.innerHTML += "all elements like html text";
and this is working and will immediately insert elements into DOM, but I can't to use innerHTML, because it will remove old listeners (for example checked checkboxes that JS will set from checked to unchecked, what is my main problem due to I have to try using append DOM function).
Try changing the code to wrap the call to CKEDITOR.replace in a setTimeout:
setTimeout(function() {
CKEDITOR.replace(inputID).setData('Type anything you want ...');
},0).
This will allow the browser time to insert the element before trying to replace it.
And I assume that inputID has a valid value in it...

Read more opens 1st one all the time

I've a page with about 10 short articles.
Each of them as a "Read More" button which when pressed displays hidden text
The issues I have at the moment is when I press the "Read More" on any of the 10 button it shows the 1st articles hidden content and not the selected one.
I think I need to set a unique ID to each article.. and the read more button be linked to it.. But I don't know how to set it.
I looked at this but couldn't get it working how to give a div tag a unique id using javascript
var WidgetContentHideDisplay = {
init:function() {
if ($('#content-display-hide').size() == 0) return;
$('.triggerable').click(function(e){
var element_id = $(this).attr('rel');
var element = $('#'+element_id);
element.toggle();
if (element.is(':visible')) {
$('.readmore').hide();
} else {
$('.readmore').show();
}
return false;
});
}
}
var div = documentElemnt("div");
div.id = "div_" + new Date().gettime().toString;
$(document).ready(function(){ WidgetContentHideDisplay.init(); });
OP Edit: Sorry, the original code wasn't in caps. I kept getting errors when trying to post, so I copied the code into Dreamweaver and it made it all caps for some reason.
Instead of selecting the element to toggle with an ID (i.e. $('#'+ELEMENT_ID)) you could setup a class for your item and use the class selection (e.g. $('.DETAILED-ARTICLE)') to select the child (or the brother, etc. depending how you built the HTML page).
In theory each ID should point to a single element but each class can be put to as many elements as you want.
If you're getting errors, read the errors and see what they are. Off of a quick read of your code, here are a couple things I noticed that will probably cause issues:
"documentElemnt" is misspelled, which will render it useless. Also, documentElement is a read-only property, not a function like you're using it.
toString is a function, not a property, without the parentheses (.toString()) it isn't going to function like you want it to.
Run the code, look at the errors in the console, and fix them. That's where you start.

have element change appreance with only javascript and CSS

attempting to have my webpage be a bit more dynamic by having the background change on some elements when a checkbox is clicked. I am trying to do this via class change and a CSS sheet. I have the following which is kicking out an error that my onclick function ins not defined (in IE9). More importantly will the webpage update if I only change the class of the object which would have a different class in the CSS file. Whats a better alternative if this does not work?
my elemenet and function
UPDATE
I made updates to both my HTML and CSS file as suggested by many. I am still getting no change in my webpage but the console is claiming that my function called from the onclick event is not defined which is a bit odd since it is. Also does this type for scripting belong in the HTML or should I pull it out and put in a seperate file. I figured since it was creating elements it belongs in the main html. Is there a cleaner more compact way of accomplishing this and not making my home screen html huge?
<tr class= 'tr.notchosen'><td><input type='checkbox' onclick='handleClick(this.id)'/></td></tr>
function handleClick(cb) {
var currentColumn = cb.parentNode
var currentRow = currentColumn.parentNode
if (currentRow.className === "chosen")
{
currentRow.className = "notchosen";
}
else
{
currentRow.className = "chosen";
}
}
and my css file is the following
tr.chosen
{
background-color:rgba(255,223,0,0.75);
}
tr.notchosen
{
background-color:rgba(255,223,0,0);
}
There are a couple of things going on here. First, your css selector is not quite right. In fact, I would suggest making the class name just "chosen" or "not chosen" and then selecting tr elements with that class.
<tr class='notchosen'>
And then you can target it from css (which was probably the original intention)
tr.notchosen
{
background-color:rgba(255,223,0,0);
}
Further, although I would not suggest using inline javascript, using your example, you should pass this if you want to work with the element and not this.id which would pass a string.
onclick='handleClick(this)'
The last part would be to sync up your javascript with the class name change
if (currentRow.className == "chosen")
{
currentRow.className = "notchosen";
}
else
{
currentRow.className = "chosen";
}

html tags changing but no change made on form

I am using the following code to change the attributes of a tag on my form
the tag
<input jwcid="licensingApprovalDate#CustomDatePicker" disabled="ognl:disabled || isLicensingApprovalDateDisabled()"
value="ognl:company.licensingApprovalDate" displayName="message:company.licensingApprovalDate"/>
the code to add new attributes to the above tag
function checkForChange(field) {
var approvalStatus = document.getElementById('licensingStatus').value;
if(approvalStatus == "Pass"){
document.getElementById('licensingApprovalDate').setAttribute("validators", "validators:maxDateToday,required");
} else {
document.getElementById('licensingApprovalDate').setAttribute("validators", "validators:maxDateToday");
}
}
this function is being called when ever licensingStatus is changed, it is working and when i inspect the element when the licensingStatus is changed the tag is changed correctly but this should add an * next to the licensingApprovalDate input box but it doesn't
Is there a way for the changes to take place the second the tag/licensinggStatus is changed?
validators is a parameter, and not an attribute. It appears in the template as an attribute because, hey, it's kinda XML.
Tapestry 3 was not designed for this level of dynamic behavior (it was cutting edge in 2003 though!). Given that its 2012, please consider an upgrade to Tapestry 5!

visibility:collapse in javascript

I'm using Ultrawebgrid for my applcation:
I'm using a textarea for listing the errors in my application in the row template when the user clicks that particular row...
So I need to have
texarea when there are any errors..... otherwise when there are no errors i dont even
want the row_template to pop up..... I'm using IE6.
I'm checking if there are any errors using javascript.so I had to use the javascript event handler:: UltraWebGrid1_BeforeRowTemplateOpenHandler(gridName, rowId, templateId)
where in I write the statements given below:
document.getElementById("TextArea2").style.visibility="collapse"
inside the above event function
1) it's showing javascript error as
"Couldnot get the visibility property:Invalid Argument"
but the row template does not pop up....... only the error's coming....
2) Is there any code to block the row template when there are no errors.??
i mean no pop_up for no errors
What's the solution for this???
DISPLAY
Use display instead of visibility. This occupies no space in your document.
document.getElementById("TextArea2").style.display = 'none'; // Turn off
document.getElementById("TextArea2").style.display = 'inline'; // Turn on
VISIBILITY
document.getElementById("TextArea2").style.visibility="hidden"; // Turn off
document.getElementById("TextArea2").style.visibility="visible"; // Turn on
By using the above code textarea won't be visible, but there will be blank space in your document having the height and width of the textarea.
Also 'collapse' value is supported only in Internet Explorer 8
Try using:
document.getElementById("TextArea2").style.display = 'none';
and (to turn it back on again)
document.getElementById("TextArea2").style.display = 'block'; // or 'inline'
You want:
document.getElementById("TextArea2").style.visibility = "hidden";
"collapse" is not a valid value for the visibility property in IE6, as your error message indicates.
Alternatively as suggested by #tvanoffsen you could set the display property to "none". This has a slightly different effect - it will not take up any space if set to "display: none", whereas setting "visibility: hidden" still takes up space.
use visible and hidden for .style.visibility attribute not block and hidden.
it works.

Categories