Why is my jQuery not adding display on second div I create? - javascript

When I try adding the first contact and submit it, it shows in the div id=contact.
The function hide/show is working then.
But as soon as I add a second contact it's not working anymore.
Seems, jQuery doesn't enter display...
function css(){
$('.contacts').css('background-color', 'lightblue');
}
function visibility() {
$("#vis").click(function(){
$(".description").toggle();
return false;
});
};
$( document ).ready(function() {
$("form").submit(function (event) {
var fname = $('#fname').val();
var lname = $('#lname').val();
var desc = $('#desc').val();
$('.contacts').append( "<div id='contact'>"+fname+"<br>"+lname+"<br><button id='vis'>Show/Hide</button><div class='description' style='display:;'>"+desc+"</div></div>");
// alert(fname);
event.preventDefault();
css();
visibility();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="get">
<fieldset>
<legend>Personal information:</legend>
First name: <input type="text" name="fname" id="fname"><br>
Last name: <input type="text" name="lname" id="lname"><br>
</fieldset>
<fieldset>
<legend>Description:</legend>
<textarea id="desc" value="desc"> </textarea><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<div class="contacts"> </div>
Any help would be appreciated, thanks.

As I wrote in comment - You can't have multiple elements with the same ID in html. You also don't have to add listeners for each button. You can add listener for body and selector as second parameter (see attached code).
function css(){
$('.contacts').css('background-color', 'lightblue');
}
$( document ).ready(function() {
//this way you don't need to add listener for each button
$('body').on('click', '.vis', function() {
$(this).closest('.contact').find('.description').toggle();
});
$("form").submit(function (event) {
var fname = $('#fname').val();
var lname = $('#lname').val();
var desc = $('#desc').val();
$('.contacts').append( "<div class='contact'>"+fname+"<br>"+lname+"<br><button class='vis'>Show/Hide</button><div class='description'>"+desc+"</div></div>");
event.preventDefault();
css();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="get">
<fieldset>
<legend>Personal information:</legend>
First name: <input type="text" name="fname" id="fname"><br>
Last name: <input type="text" name="lname" id="lname"><br>
</fieldset>
<fieldset>
<legend>Description:</legend>
<textarea id="desc" value="desc"> </textarea><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<div class="contacts"> </div>

Related

How do I make each new output appear in a new box?

I would like for every different item inputted to be outputted in a new box.
<!DOCTYPE html>
<html>
<body>
Form to get the input
<form id="form1">
<input name="item" type="text" size="20">
</form>
Box that should be duplicated to hold the new input.
<div class="box">
<p class="output"></p>
<div>
<button onclick="outputItem()">Add</button>
javascript:
<script>
function outputItem() {
var x = document.getElementById("form1");
item = x.elements.namedItem("item").value;
document.getElementById("output").innerHTML=item;
</script>
</body>
</html>
I am not sure if this is even close to what you want, but give this a try:
function outputItem() {
var els = document.querySelectorAll("#form1 input");
var box = document.querySelector('.box');
box.innerHTML = '';
els.forEach(
function(el) {
var newEl = document.createElement('div');
newEl.innerHTML = el.value;
box.appendChild(newEl);
}
);
}
<form id="form1">
<input name="item" type="text" size="20" value="item"><br/>
<input name="eggs" type="text" size="20" value="eggs"><br/>
<input name="milk" type="text" size="20" value="milk"><br/>
<input name="grains" type="text" size="20" value="grains"><br/>
<input name="legumes" type="text" size="20" value="legumes"><br/>
</form>
<button onclick="outputItem()">Add</button>
<hr/>
<div class="box"></div>
This creates a new <div> for every input and copies the .value from the <input> into the new <div>. Then it adds the <div> into the output area.

How to create a unique id from the first two fields in the form?

I created a form with three fields first_name, Last_name, city and in the fourth field, I am having an Id column which is read-only. When the user fills the first three fields in the form, before submitting it should generate an id in the fourth column but here it should use the first two alphabets that are in the fields to generate an Id
For eg. First_name = Roid, Last_name = Steve, city = California then in the fourth field it should automatically generate this id = rostca (all the first two alphabets)
How to achieve this?
Here is a JavaScript version to answer to your issue.
(function () {
populate();
})();
function populate () {
var str = "";
Array.from(document.getElementsByClassName("inputs")).forEach(function (element) {
str += element.value.substr(0, 2).toLowerCase();
});
document.getElementById("output").value = str;
}
<div>
<input type="text" class="inputs" value="Roid" oninput="populate();" />
<input type="text" class="inputs" value="Steve" oninput="populate();" />
<input type="text" class="inputs" value="California" oninput="populate();" />
<input id="output" type="text" readonly disabled />
</div>
Here is a jQuery answer to your issue.
$(function () {
populate();
$(".inputs").on("input", function() {
populate();
});
});
function populate () {
var str = "";
$(".inputs").each(function () {
str += $(this).val().substr(0, 2).toLowerCase();
});
$("#output").val(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" class="inputs" value="Roid" />
<input type="text" class="inputs" value="Steve" />
<input type="text" class="inputs" value="California" />
<input id="output" type="text" readonly disabled />
</div>
Check below code,
function TextChanged(){
var first_name = document.getElementById("first_name").value;
var Last_name = document.getElementById("Last_name").value;
var city = document.getElementById("city").value;
document.getElementById("id").value = first_name.substring(0, 2) +Last_name.substring(0, 2) +city.substring(0, 2);
}
<input type="text" id="first_name" onblur="TextChanged()">
<input type="text" id="Last_name" onblur="TextChanged()">
<input type="text" id="city" onblur="TextChanged()">
<input type="text" id="id" readonly>
Check here jsbin demo, https://jsbin.com/qegazab/edit?html,js,console,output

After file type validation using JS for an HTML Form, control should stay on the same page if invalid

I have an html form where for file types I want only pdf, docx and doc files. I am successfully able to validate, but on click of OK button, I do not want to post the form if it is invalid. Currently, it is going to connection.php. It should only go to connection.php when I have passed the validation successfully.
<form method="POST" action="connection.php" enctype="multipart/form-data" onsubmit="function()">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
</form>
<script>
$(document).ready(function () {
$('input[type=file]').change(function () {
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(docx|doc|pdf)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Please select correct file format');
} }); });
</script>
Use onsubmit event:
<form method="POST" action="connection.php" enctype="multipart/form-data" onsubmit="return validate()">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
<input type="submit" value="Upload book">
</form>
<script>
function validate() {
var val = document.getElementById('bookfile').value.toLowerCase();
var regex = new RegExp("(.*?)\.(docx|doc|pdf)$");
if(!(regex.test(val))) {
document.getElementById('bookfile').value = '';
alert('Please select correct file format');
return false;
}
return true;
}
</script>
<form method="POST" action="connection.php" enctype="multipart/form-data" id="myform">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
</form>
<script>
var isValid = false;
$(document).ready(function () {
$('input[type=file]').change(function () {
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(docx|doc|pdf)$");
isValid = !!(regex.test(val));
if(!isValid) {
$(this).val('');
alert('Please select correct file format');
} }); });
$("#myform").submit(function(e) {
if (!isValid) {
e.preventDefault();
}
});
</script>
I have added an id to your form. Using this id as a selector I have created a submit handler for the form. This handler checks whether isValid is false and if so, calls e.preventDefault(), which prevents the form from submitting. If isValid was true, then e.preventDefault() will not be called, therefore the form submits. isValid is initialized with false and is evaluated on input[type=file] change.

Show alert (Text Field is empty) on submit Html/JavaScript

How to get an Alert on Submit when I left a TextBox empty And It Should Turn To the Next page on submit.
Must Reply,
Thank You.
You can try this :
HTML :
<form action="" method="POST" id="myForm">
<input id="myInput" type="text" />
<input type="submit" />
</form>
(Replace the action attribute by the url of your destination page, the one you call the "next page").
JS (without jQuery):
var myForm = document.querySelector('#myForm');
var myInput = document.querySelector('#myInput');
myForm.addEventListener('submit', function(pEvent) {
if(myInput.value === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
//Do whatever you want
}
});
JS (with jQuery) :
var myForm = $('#myForm');
var myInput = $('#myInput');
myForm.on('submit', function(pEvent) {
if(myInput.val() === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
}
});
Demo : http://jsfiddle.net/af9qvkmp/9/
Here is the demo, based on jQuery!
HTML
<form action="" method="POST" id="form">
<input id="input1" type="text" />
<input id="input2" type="text" />
<input id="input3" type="text" />
<input id="input4" type="text" />
<input id="input5" type="text" />
<input type="submit" />
</form>
JS
$(function() {
$('#form').on('submit', function(event) {
var isError = false;
$(this).find('input[type="text"]').each(function() {
if($(this).val() == '') {
console.log($(this));
isError = true;
return false;
}
});
if(isError) {
event.preventDefault();
alert("Got Error");
} else {
// Submit the form
}
});
});
In form tag write
<form action="" method="post" enctype="multipart/form-data" onsubmit="return checkform(this);">
This is your input field
<input type="text" name="reviewValue" value="" id='starRate2' required>
Javascript Code:
<script language="JavaScript" type="text/javascript">
function checkform ( form ){
if (form.reviewValue.value == "") {
alert( "Please choice your Rating." );
form.reviewValue.focus();
return false ;
}
return true ;
}
</script>

How to make a required field be invisible if valid?

I have this kind of html:
<form method="post" action="register">
<input type="text" name="name" required />
<button>Next</button>
</form>
When I click the Next button, I want to hide the Name field, but only if it is valid(not empty) and I don't want to submit the form. How can I do this with plain JavaScript?
If you know a way with jQuery, please write that too. Thanks.
Try this:
$('button').click(function() {
var check = $('#name').val();
if (check == '') {
$('#name').hide();
}
})
If the input has no content, it will be hidden.
document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault();
var input = e.target.firstElementChild;
if(!input.validity.valueMissing) {
input.style.display = 'none';
}
}, false);
<form method="post" action="register">
<input type="text" name="name" required />
<button>Next</button>
</form>
Assuming that you will change "form button" for the ID of the button, and "form input" for the ID of the input. The jQuery code would be something like this:
$("form button").click(function() {
if ($("form input").val() != "")
$("form input").hide();
});
Try this:
<form method="post" action="register">
<div id="steps1">
<input id="txtname" type="text" placeholder="enter name here" name="name" />
<input id="btnNext" type="button" value="next" />
</div>
<div id="complete" style="display:none;">
<input type="text" name="age" placeholder="enter age here" />
<input type="submit" value="submit" />
</div>
</form>
$(document).ready(function () {
$("#btnNext").click(function () {
if ($("#txtname").val() != "") {
$("#steps1").hide();
$("#complete").show();
}
});
});
In jQuery:
$("button").click(function() {
if ($('input[name=name]').val() != '') {
$('input[name=name]').fadeOut(); // Or hide, or css('display', 'none')
}
});
Make class e.g. "validate", which you can attach to your form after clicking Next.
Then in CSS:
.validate input:valid {
display: none;
}
Try onsubmit event:
var validate = function(form) {
var toSubmit = true;
if (form.name.value) { //has some text
form.name.style.display = "none"; //hide the input field
} else {
toSubmit = false;
}
return toSubmit;
};
<form method="post" action="register" onsubmit='return validate(this);'>
<input type="text" name="name" required />
<button>Next</button>
</form>
EDIT
Try blur event:
var validate = function(box) {
if (!box.value) {
alert('This field is required');
box.focus();
}
};
<form method="post" action="register">
<input type="text" name="name" onblur='validate(this);' />
<button>Next</button>
</form>
Read these to understand the code and why.
document.querySelector
EventTarget.addEventListener
onsubmit
event.preventDefault
Constraint validation HTML5
document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault();
var input = e.target.firstElementChild;
if(!input.validity.valueMissing) {
input.style.display = 'none';
}
}, false);
<form method="post" action="register">
<input type="text" name="name" required />
<button>Next</button>
</form>

Categories

Resources