Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put an image element Dynamically by Javascript

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Form_Valid_JS</title>
</head>

<body>
<form name="form" id="form">
<label style="font-size:18px"><strong> Name</strong> </label><br><br><div id="error"> </div>
<input type="text" id="fname" name="fname" placeholder="First Name" pattern="[a-zA-Z\s]{0,10}" onBlur="fvalidity()" onFocus="Focus()">; 
<input type="text" id="lname" name="lname" placeholder="Last Name" pattern="[a-zA-Z\s]{0,10}" onBlur="lvalidity()">
<input type="submit">
</form>


</body>
</html>
<script>
function fvalidity()
{
    var txt="";
    if( document.getElementById("fname").validity.patternMismatch)
    {
        txt="*Only Alphabet max 10 Characters.";
    }
    if(document.getElementById("fname").value=="")
    {
        txt="Field is Empty!!";
    }
    if(txt!="")
    {
        img();
        var s=document.getElementById("error");
        s.innerHTML=txt;
        s.style.visibility="visible";
    }
}
function img()
{
    var sample=document.createElement("img");
    var t= document.createAttribute("src");
    t.value="../cross_script.png";
    sample.setAttributeNode(t);
    var id=document.createAttribute("id");
    id.value="img";
    sample.setAttributeNode(id);
    document.getElementById("form").appendChild(sample);

}
</script>

I want to put an image dynamically after the each input field to show the Tick or Cross sign. But when i do that it put the image in the last after the submit button what is the correct procedure to put a image after each input field dynamically. I mean i make a function and later i call it when doing validation. not. dynamically i make the Elements and tags and apply Cs on it and show on the page after each input field.

like image 976
Saad Saadi Avatar asked Jun 11 '26 12:06

Saad Saadi


1 Answers

In that case you need to pass the reference to the input field after which the image to be inserted like

function img(target) {
    var sample = document.createElement("img");
    sample.src = "../cross_script.png";
    document.getElementById("form").appendChild(sample);
    if (target.nextSibling) {
        target.parentNode.insertBefore(sample, target.nextSibling)
    } else {
        target.parentNode.appendChild(sample)
    }
}

then

img(document.getElementById("fname"));
like image 76
Arun P Johny Avatar answered Jun 14 '26 03:06

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!