Getting html listitem style value for comparison - javascript

Hi i have a html list item thats hidden by default on the page that contains a date picker:
<li id="hiddenListItem" style="display:none;">
<label for="returning">Returning:</label>
<input type="text" id="returning" required/>
<span class="form_hint">Proper format "12/04/2014"</span>
</li>
If the user selects that they want a return journey then the list item is made visible:
<script>
function needReturn() {
var item = document.getElementById("hiddenListItem");
item.style.display = 'list-item';
}</script>
<script>
function dontNeedReturn() {
var item = document.getElementById("hiddenListItem");
item.style.display = 'none';
}</script>
If the user click continue button then external .js file validates the form, but if they don't need a return ticket then browser displays message saying please fill in this information.
I was hoping to determine the state of the listitem style and if it was visible then show the warning else continue:
else if (returning === "")
{
var item = document.getElementById("hiddenListItem");
if(item.style.display === "list-item")
{
alert("Please enter a return date.");
}
}
I cant get the above statement to work, any help please.
HTML and JS is not my thing.

This should work:
if (item.style.display !== 'none') {
alert("Please enter a return date.");
}

Related

When using a form that takes to the main website

I am doing a form window before you get in the main website so I tried to make it so that if you don't fill any of the spaces it will open a window alert asking to fill those spaces. Plus I'd like that you would only get to the main website if you fill all the spaces but yet the button on the form window always takes to the main website without requiring filling of the camps.
On the button I wrote this:
<a href="index1.html">
<input type="button" value="Terminar" onclick = location.href='index1.html' >
</a>
and on the js window I wrote the window alert command to each one of the categories:
if(frm.name.value=="" || frm.name.value==null || frm.name.length < 3) {
alert("Please write your first name ")
frm.name.focus();
return false;
It seems you are trying to validate the an input field based on a few criteria.
Your question is not clear. Is this what you are trying to do?
function validateInput() {
if (frm.value == "" || frm.value == null || frm.value.length < 3) {
alert("Please write your first name ")
frm.focus();
} else
location.href = 'index1.html'
}
<input type="text" id="frm" placeholder="Please write your first name" />
<input type="button" value="Terminar" onClick="validateInput()">
You want something like this. In your code the input is wrapped in an a tag. so it will always trigger the event. Adding a button the trigger the event will help.
button = document.getElementById('enter');
input = document.getElementById('fill');
button.onclick = function() {
if (input.value == null || input.value == "" || input.value == " ") {
alert('Please write your first name');
} else {
window.location.href = 'index1.html';
}
};
<input id="fill">
<button id="enter">Enter</button>

How to implement Try Catch Finally Statement with form input - Javascript

I'm trying to use this to create a message that states "Please enter a number" when you hit submit on a form and there's no number in the input for "If you would like to state a specific amount type it in the box below". It's doing absolutely nothing, so I don't know what's going on. I'm still in school and this is my first class with JavaScript so I would appreciate any help you can give.
Here is the JavaScript portion:
```
// test page form exception code - Chapter 4
function verifyFormCompleteness() {
var specificAmountBox = document.getElementById("specificamount");
var completeEntry = true;
var messageElement = document.getElementById("message");
var messageHeadElement = document.getElementById("messageHead");
var validity = true;
var messageText = "";
try {
if (specificAmountBox.value == "" || specificAmountBox.value == null){
window.alert = "Please enter a number in the specific amount box";
}
}
catch(message) {
validity = false;
messageText = message;
specificAmountBox.value = ""; // removes bad entry from input box
}
finally {
completeEntry
messageElement.innerHTML = messageText;
messageHeadElement.innerHTML = "";
alert("This is happening in the finally block");
}
if (validity = true) {
return submit;
}
}
```
Here is the HTML portion:
```If you would like to state a specific amount type it in the box below:<br>
<input type="number" id="specificamount" name="specificamount">
<h1 id="messageHead"></h1>
<p id="message"></p>
<br>
<br>
```

How do i add separate elements to a list in javaScript?

Im trying to make an option, for the user to create a list of owned records. However i ran into the following problem:
When the user tries to create a list with no name, an empty/invisible element is added to the list. I want the code, to ask the user to enter a name if he leaves the prompt blank.
When elements are added, i want them to be separate and different elements. Now they are shown and displayed as one.
I hope some of you guys can help me overcome this problem. Please ask if anything seems unclear.
My present code is presented below:
function myFunction1() {
var txt;
var person = prompt("Please enter the name of your record list:");
if (person == null || person == "") {
txt = "";
} else {
txt = person + "<br>";
}
document.getElementById("myRecords").innerHTML += txt;
}
<a id="myRecords"></a>
<a id="create" onclick="myFunction1()">Create RecordList</a>
When using prompt, it's best to use a while loop to make sure that input is entered. This will continue cycling the message until the user enters sufficient information. When a user hits cancel a null value is returned. Within the while loop we check if person is null, and if that is the case we immediately return.
To add separate elements you can use document.createElement and then append that element to your selected parent through the use of the appendChild method.
In the below code I took the liberty of converting your myRecords div into a ul or unordered list tag. When names are entered they are added as li ( list item ) children to this tag.
function myFunction1() {
var person, ul = document.getElementById("myRecords"), li = document.createElement("li");
while (!person) {
person = prompt("Please enter the name of your record list:");
if (person == null) return;
}
li.textContent = person;
ul.appendChild(li);
}
myFunction1();
myFunction1();
<ul id="myRecords"></ul>
If you don't want to use a list, you can simply update the markup and change what you are appending. In the below myRecords is an a tag. We append a div with the appropriate text to this anchor tag as we did in the above.
function myFunction1() {
var person, a = document.getElementById("myRecords"), div = document.createElement("div");
while (!person) {
person = prompt("Please enter the name of your record list:");
if (person == null) return;
}
div.textContent = person;
a.appendChild(div);
}
myFunction1();
<a id="myRecords" href="#"></a>
You should use something like an (un)ordered list (<ol>, <ul>) and then append list item (<li>) containing the name in an <a> tag if need be. If you want to append an empty item when a name isn't entered, you don't have to use an if statement.
const getRecordList = () => document.getElementById('recordList');
const getCreateButton = () => document.getElementById('create');
function promptInput(value = '') {
const message = 'Please enter the name of your record list:';
let name = '';
while (name === '') {
name = prompt(message, value);
}
return name;
}
function createListItem(name) {
const listItem = document.createElement('li');
listItem.innerHTML = `<a onclick="updateRecord(this)">${name}</a>`;
return listItem;
}
function createRecord() {
const name = promptInput();
if (!name) return;
getRecordList().appendChild(createListItem(name || ''));
}
function updateRecord(li) {
li.innerHTML = promptInput(li.innerHTML);
}
<h2>Record List</h2>
<ol id="recordList"></ol><hr>
<button id="create" onclick="createRecord()">Create</button>
you need to change your JS to the following:
function myFunction1() {
var txt;
var person = prompt("Please enter the name of your record list:");
if (person == "") {
alert('Please enter a name');
return;
} else if(person == null){
return;
} else {
txt = person;
}
var span = document.createElement('span');
span.setAttribute('class', 'myElement');
span.innerHTML = txt;
document.getElementById("myRecords").appendChild(span);
}
<a id="myRecords"></a>
<a id="create" onclick="myFunction1()">Create RecordList</a>
With createElement a new element is created, to add a class you can use setAttribute and then you append it as a child to your myRecords element via appendChild.
function myFunction1() {
let person = prompt("Please enter the name of your record list:");
if (person) {
let div = document.createElement('div');
div.innerText=person;
document.getElementById("myRecords").appendChild(div);
}else{
alert('Please enter a name');
}
}
<a id="myRecords"></a>
<a id="create" onclick="myFunction1()">Create RecordList</a>
You can createElement and appendChild to add desired elements.
Without knowing exactly what you're trying to accomplish, this is the solution I came up with for you:
function myFunction(prompt_text) {
var txt;
var list;
var person;
if (prompt_text != '' && prompt_text != undefined) {
person = prompt(prompt_text);
} else {
person = prompt("Please enter the name of your record list:");
}
if (person == null || person == "") {
txt = "";
} else {
txt = '<li>' + person + "</li>";
}
if (txt != '') {
document.getElementById("myRecords").innerHTML += txt;
} else if(person != null){
myFunction("Names cannot be blank, please enter the name of your record list:");
} else {
return;
}
}
<ul id="myRecords"></ul>
<a id="create" onclick="myFunction()">Create RecordList</a>
I've modified the container that you're putting the data into to be an unordered list <ul></ul> to better facilitate having multiple entries in it, and auto-appended the <li></li> DOM so that the list does all of the work for you.
I've also changed the function to accept prompt_text as a parameter, so you can recursively call the function if they don't enter text.
EDIT: updated the code to understand the null returned when a user clicks the cancel button, which removes the error that was created by the code I originally posted.
The final change is the recursive function call I mentioned above. If the txt variable is empty, the function calls itself with new prompt_text allowing you to let the user know WHY they didn't do it right, as well as giving them another opportunity to correct that.

Toggle visibility of html using javascript checkbox event

I've cobbled together these javascript functions to hide the delivery address fields on my shopping cart address form if goods are going to billing address. The functions toggle visibility of html wrapped by ..
function getItem(id) {
var itm = false;
if(document.getElementById)
itm = document.getElementById(id);
else if(document.all)
itm = document.all[id];
else if(document.layers)
itm = document.layers[id];
return itm;
}
function showHideItem(id) {
itm = getItem(id);
if(!itm)
return false;
if(itm.style.display == 'none')
itm.style.display = '';
else
itm.style.display = 'none';
return false;
}
It works fine if were loading a new address form, the problem I have is if they submit the form with checkbox ticked, and validation fails, the form reloads with the checkbox ticked but unfortunately the fields are visible so now the removing the checkbox hides the fields!!
<tr><td class="white"><strong>Delivery Address</strong></td>
<td>Tick <input Type="checkbox" id="deliver_same" value="yes" onClick="showHideItem('delAddress')" />
If delivery address is billing address</td></tr>
<tbody id="delAddress">
<tr><td>Address line 1</td><td><input class="text" name="saddr1" value="" /></td></tr>
...
<tr><td>Post /Zip Code</td><td><input class="text" name="spostalcode" value="" /></td></tr>
</tbody>
I guess what I need is an onload event which hides the fields if checkbox is ticked when the form loads. Having just written that, I might have a go but not confident. Please, no mention of jquery, its not an option at this point of project.
function checkDeliverSame() {
var deliverSame = getItem('deliver_same');
var deliveryAddress = getItem('delAddress');
if (deliverSame.checked) {
deliveryAddress.style.display = 'none';
} else {
deliveryAddress.style.display = 'block';
}
}
checkDeliverSame(); /* This runs the function on page load */
Put that function, along with your getItem function, right above the </body> tag, and call it in the checkbox input onclick. You will also need to change the id#delAddress element from a tbody to a div so that the getItem function will work on it.
Here's a fiddle: http://jsfiddle.net/JuNhN/1/
I modified Josh's function to make it more generic, prefer document.getElementById() too as it fits in better with itm.style.display. I don't entirely trust checkDeliverSame(); going for a direct call in the html shortly after the closing tag.
function checkHiddenRows(id) {
deliverSame = getItem('deliver_same');
itm = document.getElementById(id);
if (deliverSame.checked == true) {
itm.style.display = 'none';
} // else { alert('Checkbox not checked') } // Verify the checkbox state
}
<script>checkHiddenRows('deliveryAddress');</script>
The form is now working as intended.

else if statement in javascript not able to display validation message

I am having trouble displaying strings depending on the if/else statements in my validation.
If you look at the code below, if the if statement is met, then it displays the message which is fine, but then when I make sure the if statement is met and deliberately fail the else if statement, instead of displaying a message, it just displays a blank. Why is it not displaying a message for when else if statement is met in javascript validation below:
function editvalidation() {
var isDataValid = true;
var currentAssesO = document.getElementById("currentAssessment");
var noStudentsO = document.getElementById("addtextarea");
var studentAssesMsgO = document.getElementById("studentAlert");
studentAssesMsgO.innerHTML = "";
if (currentAssesO.value == ""){
$('#targetdiv').hide();
studentAssesMsgO.innerHTML = "Please Select an Assessment to edit from the Assessment Drop Down Menu";
isDataValid = false;
}else if (noStudentsO.value == ""){
$('#targetdiv').hide();
studentAssesMsgO.innerHTML = "You have not Selected any Students you wish to Add into Assessment";
isDataValid = false;
}
else{
studentAssesMsgO.innerHTML = "";
}
return isDataValid;
}
UPDATE:
HTML:
SELECT BOX (Options are appended into this box):
<select multiple="multiple" name="addtextarea" id="studentadd" size="10">
</select>
DROP DOWN MENU:
<select name="session" id="sessionsDrop">
<option value="">Please Select</option>
<option value='20'>EWYGC - 10-01-2013 - 09:00</option>
<option value='22'>WDFRK - 11-01-2013 - 10:05</option>
<option value='23'>XJJVS - 12-01-2013 - 10:00</option>
</select> </p>
ALERT MESSAGE:
<div id='studentAlert'></div>
Reuirements for validation:
If drop down menu is empty, then display message that assessment needs to be select from drop down menu in alert message div.
If drop down menu is not empty, then check to see if the select box contains any options, if select box contains no options, then replace div alert message stating no students have been selected to add to assessment
If drop down menu is not empty and select box is not empty (or in other words contains an option), then div alert message is just an empty string ""
Rephrase your JavaScript this way:
function editvalidation() {
var isDataValid = true;
var currentAssesO = document.getElementById("currentAssessment");
var noStudentsO = document.getElementById("addtextarea");
var studentAssesMsgO = document.getElementById("studentAlert");
var errorMsg = "";
studentAssesMsgO.innerHTML = "";
if (currentAssesO.value == "" || noStudentsO.value == "") {
$('#targetdiv').hide();
isDataValid = false;
if (currentAssesO.value == "") {
errorMsg += "Please Select an Assessment to edit from the Assessment Drop Down Menu";
}
if (noStudentsO.value == "") {
errorMsg += "You have not Selected any Students you wish to Add into Assessment";
}
studentAssesMsgO.innerHTML = errorMsg; // Plus whatever styling for messages.
}
return isDataValid;
}
Updated answer
Please include jQuery by putting this in the <head> section.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Update your script:
function editvalidation()
{
if ($("#sessionsDrop").val()=="")
$("#studentAlert").html("Assessment needs to be filled.");
if ($("#sessionsDrop").val()!="" && $("#studentadd").children().length==0)
$("#studentAlert").html("No students have been selected to add to assessment.");
if ($("#sessionsDrop").val()!="" && $("#studentadd").children().length!=0)
return true;
return false;
}
Here is the magic:
else {
studentAssesMsgO.innerHTML = "";
alert(noStudentsO.value); // tell me why I'm in this block
}

Categories