Styling in HTML with CSS while using Javascript - javascript

How do I transfer the style code to my external css file? I think using .gamelist won't work because of the <form> or <input> stuff. I know that I can just leave the style in the html file but I like everything to be as neat and organized as possible.
Here's the html code:
<div id="sidebar">
<p class="gamelist">
<FORM>
<input type="image" src="images/mariosadv.jpg" border="2" style="border:2px solid black;max-width:150px;" value="Enter Protected Area" onClick="passWord()">
</FORM>
<FORM>
<input type="image" src="images/mariosadv2.jpg" border="2" style="border:2px solid black;max-width:150px;" value="Enter Protected Area" onClick="passWord()">
</FORM>
</div>
Here's my simple Javascript function:
function passWord() {
var testV = 1;
var pass1 = prompt('Please Enter Your Password',' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "letmein") {
alert('You Got it Right!');
window.open('mariosadv.html');
break;
}
testV+=1;
var pass1 =
prompt('Access Denied - Password Incorrect, Please Try Again.','Password');
}
if (pass1.toLowerCase()!="password" & testV ==3)
history.go(-1);
return " ";
}
Here's the css I tried:
.gamelist img {
display: block;
border: 2px solid black;
width:150px;
margin: 5px 0px 5px 0px;
}
This is what I have with Javascript
http://i.imgur.com/QVc6Dgu.jpg
And this is what I want but without the Javascript
http://i.imgur.com/sNX3Els.jpg
If any additional information is needed please ask before rejecting my question. Thanks.

You'll need to be styling the .gamelist [type=image] instead of .gamelist img, since the img only refers to tags with that name (not to images in general).
EDIT Here's what your HTML should look like:
<div class="gamelist">
<FORM>
<input type="image" src="images/mariosadv.jpg" value="Enter Protected Area" onClick="passWord()">
</FORM>
<FORM>
<input type="image" src="images/mariosadv2.jpg" value="Enter Protected Area" onClick="passWord()">
</FORM>
</div>

As metadept wrote, you'll need to use following CSS selector: input[type='image'].
Be aware that .gamelist input[type='image'] don't select the needed input fields because they haven't the class gamelist.
For a CSS Selector overview use: http://www.w3schools.com/cssref/css_selectors.asp
And please do not use client side authentification!!!

Related

Check box not working on form before allowed to submit

Hello guys trying to get my checkbox to need to be clicked before submitting my button which is an onclick not submit??
<form>
<p>
<input style="padding:14px; -webkit-border-radius: 30px; -moz-border-radius: 30px; border-radius: 30px; width: 300px; border: none;" placeholder="Enter Date Here... e.g 17/05/1981" />
</p>
<p>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat" required="true"> <label style="color: #fff; font-size: 10px;"> Please Accept Terms</label></p>
<p><a id="generateButton" href="generate.html" class="progress-button red" data-loading="Creating..." data-finished="Start Over" data-type="background-vertical" onclick="getRandomImage()">Start Search</a></p>
</form>
Unfortunately HTML5 does not provide an out-of-the-box way to do that.
However, using jQuery, or javascript, you can easily control if a checkbox group has at least one checked element.
function myFunction() {
document.getElementById("myCheck").required = true;
}
<form action="/action_page.php">
Checkbox: <input type="checkbox" id="myCheck" name="test">
<input type="submit" onclick="myFunction()">
</form>
You can add logic to your clickHandler to check that the box is checked. So instead of calling getRandomImage() directly you add some logic to conditionally call the function.
function clickHandler() {
// get the checkbox element from the DOM
const checkboxElement = document.getElementById('vehicle3');
// see if the checkbox is checked
if (checkBoxElement && checkBoxElement.checked) {
getRandomImage();
} else {
console.log("The checkbox wasn't checked!");
}
}
// add the handler to the button
document.getElementById('generateButton').addEventListener('click', clickHandler);

class name not showing when trying to validate email

I have a form the is trying to validate email. If the email is incorrect the class for the input does not show. Below is the code for the html:
<div class="email-entry desktop-container">
<div id="a"></div>
<form name="form1" action="#">
<input id="test" type="text" name="text1" placeholder="Email Address" value="" onclick="return ValidateEmail(document.form1.text1)">
<input type="image" src="images/icon-arrow.svg" alt="submit">
<p id="addedText"></p>
</form>
and below I have implemented the following javascript:
function ValidateEmail(inputText) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (inputText.value.match(mailformat)) {
alert("You have entered a correct email addresss")
document.form1.text1.focus();
return true;
} else {
// var img = document.createElement('img');
// img.src = "/images/icon-error.svg"
document.getElementById("addedText").innerHTML += "This is the wrong email address";
document.getElementByClassName("invalidEmail")
// alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
the css I am trying to activate is the following:
.invalidEmail {
border: 1px solid red;
background-image: url("/images/icon-error.svg");
background-repeat: no-repeat;
background-position: 75% 25%;
}
At the end of the day I want the an image to appear in the form like this. . The issue is nothing seems to appear.
To add a class to your input element, you need to use element.classList.add and to remove it you need element.classList.remove.
Also, document.getElementsByClassName("invalidEmail") will get you all the elements which contain invalidEmail classname. So it is not required here
Have gone through the repo which you mentioned:
CSS specificity is one of the culprit here. Adding !important will work fine now (check border in the snippet) but ideally you should read about it and then fix the css without using !important
It seems you are not hosting your project and opening the index.html file directly. Host your project on some server (e.g. localhost) and it should work fine (python -m SimpleHTTPServer is a simple command to help you spawn a local server quickly which you can use but there are others as well).
function ValidateEmail was not using proper regex test for email testing. Read here for more details
Have tried to fix it for you
function ValidateEmail(inputText) {
var mailformat = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;;
if (mailformat.test(inputText.value)) {
document.getElementById("addedText").innerHTML = "";
alert("You have entered a correct email addresss")
//document.form1.text1.focus();
document.getElementById("test").classList.remove("invalidEmail")
return true;
} else {
// var img = document.createElement('img');
// img.src = "/images/icon-error.svg"
document.getElementById("addedText").innerHTML = "This is the wrong email address";
document.getElementById("test").classList.add("invalidEmail")
// alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
.invalidEmail {
border: 1px solid red !important;
/*Check here*/
background-image: url("https://image.flaticon.com/icons/png/128/752/752755.png");
background-repeat: no-repeat;
background-position: 75% 25%;
background-size: 12px 12px;
}
<div class="email-entry desktop-container">
<div id="a"></div>
<form name="form1" action="#">
<input id="test" type="text" name="text1" placeholder="Email Address" value="" onclick="return ValidateEmail(document.form1.text1)">
<input type="image" src="images/icon-arrow.svg" alt="submit" >
<p id="addedText"></p>
</form>
</div>
Hope it helps. Revert for any doubts.
Note: This is how icon image and red boundary is coming for me

Is it Possible to make a button as File upload Button?

I am new in php. I have a form on which i place a button Value as Upload MB when user click on this button it redirects on a web form where i place a file upload control and user upload file here.
Here is image
After clicking this button user redirect on this form
here user upload file.
MY QUESTION
Is it possible that can i make my button Upload Mb as file upload button? Can it works like file upload control button?
Actually i want to save user time. I want that when user click on Upload MB button it not redirects on Form. But when user Click on Upload MB button it allow to user to upload file and open browsing window. After that when user upload file it redirects on form.
Can you guys tell me it is possible or not?
You can keep a <input type='file' hidden/> in your code and click it using javascript when the user clicks on the "Upload MB" button.
Check out this fiddle.
Here is the snippet.
document.getElementById('buttonid').addEventListener('click', openDialog);
function openDialog() {
document.getElementById('fileid').click();
}
<input id='fileid' type='file' hidden/>
<input id='buttonid' type='button' value='Upload MB' />
Here is the complete code.
<html>
<head>
<script>
function setup() {
document.getElementById('buttonid').addEventListener('click', openDialog);
function openDialog() {
document.getElementById('fileid').click();
}
document.getElementById('fileid').addEventListener('change', submitForm);
function submitForm() {
document.getElementById('formid').submit();
}
}
</script>
</head>
<body onload="setup()">
<form id='formid' action="form.php" method="POST" enctype="multipart/form-data">
<input id='fileid' type='file' name='filename' hidden/>
<input id='buttonid' type='button' value='Upload MB' />
<input type='submit' value='Submit' />
</form>
</body>
</html>
my 2 cents to the topic: all in code, no input needs to be added to the page.
function onClickHandler(ev) {
var el = window._protected_reference = document.createElement("INPUT");
el.type = "file";
el.accept = "image/*";
el.multiple = "multiple"; // remove to have a single file selection
// (cancel will not trigger 'change')
el.addEventListener('change', function(ev2) {
// access el.files[] to do something with it (test its length!)
// add first image, if available
if (el.files.length) {
document.getElementById('out').src = URL.createObjectURL(el.files[0]);
}
// test some async handling
new Promise(function(resolve) {
setTimeout(function() { console.log(el.files); resolve(); }, 1000);
})
.then(function() {
// clear / free reference
el = window._protected_reference = undefined;
});
});
el.click(); // open
}
#out {
width: 100px; height: 100px; object-fit: contain; display: block;
}
/* hide if it would show the error img */
#out[src=''] {
opacity: 0;
}
<img src="" id="out" />
<button onClick="onClickHandler(event)">select an IMAGE</button>
Note: the el might get garbage collected, before you process all data - adding it to window.* will keep the reference alive for any Promise-handling.
I would suggest to convert button to label. apply the css to label so that it looks like button.
e.g. -
<input type="file" id="BtnBrowseHidden" name="files" style="display: none;" />
<label for="BtnBrowseHidden" id="LblBrowse">
Browse
</label>
Bootstrap Way
.choose_file {
position: relative;
display: inline-block;
font: normal 14px Myriad Pro, Verdana, Geneva, sans-serif;
color: #7f7f7f;
margin-top: 2px;
background: white
}
.choose_file input[type="file"]{
-webkit-appearance:none;
position:absolute;
top:0;
left:0;
opacity:0;
width: 100%;
height: 100%;
}
<div class="choose_file">
<button type="button" class="btn btn-default" style="width: 125px;">Choose Image</button>
<input name="img" type="file" accept="image/*" />
</div>
<html>
<body>
<input type="file" id="browse" name="fileupload" style="display: none" onChange="Handlechange();"/>
<input type="hidden" id="filename" readonly="true"/>
<input type="button" value="Upload MB" id="fakeBrowse" onclick="HandleBrowseClick();"/>
</body>
<script>
function HandleBrowseClick()
{
var fileinput = document.getElementById("browse");
fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("browse");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;
}
</script>
</html>
There's an experimental feature that does exactly what you are looking for. You can take a look at it here: https://developer.mozilla.org/en-US/docs/Web/API/Window/showOpenFilePicker

Php Clear textbox when user checks a checkbox

at the moment I am trying to add some functionality for a user to be able to submit an anonymous suggestion. I am trying to clear a textbox that contains the users name when the user checks the checkbox. However my code does not clear the checkbox when checked. is there a way to clear the checkbox before the form is submitted?
Thanks
<div>
<label style="display: inline-block; margin-left: 10px; letter-spacing: 2px; color: #007A8E;">
<div align="left"><b>Name:</b> </div>
</label>
<div align="left">
<input type="checkbox" style=" margin-left: 110px; outline: 1px solid #0078AE; " name="Anonymous" value="Anonymous" onClick="CheckAnon">
</div>
<label style="margin-left: 2px; color: #0078AE;">
<div align="left">Anonymous</div>
</label>
<div align="left">
<?
function CheckAnon()
{
if(isset($_POST['Anonymous']) == 'Anonymous')
{
$anonFirstName="Anon";
$anonLastName="Anon";
}
else if (isset($_POST['Anonymous']) != 'Anonymous')
{
$anonFirstName = $firstName;
$anonLastName= $lastName;
}
}
?>
</div>
</div>
<div align="left">
<input name="firstname" style="height: 34px; width: 268px; margin-left: 10px; margin-top: 5px; color: #007A8E;
border: 1px solid #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;" type="text"
value="<? echo $anonFirstName?> <? echo $anonLastName?>">
</div>
You can do this at client side using jquery or javaScript.
Assume this text box:
<input type="text" id="fname" />
JavaScript Method:
<script type="text/javascript">
function clearTextBox() {
// Code to clear textbox on Checkbox tick
var textname = document.getElementById("fname"); //get textbox id
textname.value = ""; // clear the textbox
}
</script>
You can do it in PHP as you want.
But, doing it in jQuery is quite simple.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function(){
$("#Anonymous").change(function(){
if ($(this).is(':checked')) {
$("#firstname").val('');
}
});
});
</script>
You are confusing clientside scripting (JavaScript in your case) with what the server receives (PHP).
The function you call:
onClick="CheckAnon"
Does not exist on the client. Also use: onClick="CheckAnon();"
There are more problems in your code. I advice you to use Firefox and look in the errorlog of javascript. This will help you a lot to trace the bugs.
Also make sure you understand what happens in the client (browser), and the server (after you post a form)
I think you need to clear that up first before you start clearing textboxes with JavaScript)

How to show/hide a div with javascript

I'm currently making a registration page for a site and need to show a typical password confirmation message. How would I make a script to hide and show a div?
This is as far as I've got:
<html><head>
<script language="javascript">
function correctpassword()
var password="password"
var confirmpassword="confirmpassword"
if (password1 != password2)
{
showcss="unconfirmed"
}
else
{
showcss="confirmed"
}
</script>
</head>
<body>
<form>
<u>Personal Details</u>
First Name: <input type="text" id="firstname">
Last Name: <input type="text" id="lastname">
Date of Birth:
Gender: Male Female
<u>Login Details</u>
Email Adress:<input type="text" id="email">
Username:<input type="text" id="username">
<!--check avalibility-->
Password:<input type="text" id="password">
Confirm Password:<input type="text" id="confirmpassword">
<!--Javascript if "password" doesnt equal "confirm password" showcss passwords don't match-->
<button type="button" onclick="correctpassword()">Display Date</button>
</form>
</body>
</html>
PS:The variables may be wrong.
Assuming you are talking about hiding / showing a div, spanor other similar element in HTML, you can use the jQuery JavaScript framework. For example:
$('#element_to_show').show();
$('#element_to_hide').hide();
You can trigger the hide / show via events, e.g. key press or user leaving the input element, in jQuery as well.
Control your styles and appearance with className property that applied to class markup attribute.
Try to avoid .style property of the elements and add/remove some classes instead. It will give you more control and simplify maintenance in the future.
in css:
.show{
display:block;
}
.box{
display:none;
}
in html:
<div id="passConfirm"></div>
<div id="box"></div>
in your script:
var confirmEl,
confirmBox;
confirmEl = document.getElementById('passConfirm');
confirmBox = document.getElementById('box');
confirmEl.addEventListener('click', showBox, false);
function showBox () {
confirmBox.className += ' show';
}
As mentioned, you can use some libraries that helps to work with DOM or write your own functions helping to add and remove some classes, check for hasClass method etc.
I'm on my phone, hence the short answer.
Easiest way is to get the id of the element like document.getElementById and place that into a variable.
Then use the style property like
Obj.style.display = "none";
To hide it.

Categories