JavaScript - how to change checkbox background? - javascript

I want to change background of checkbox without using jQuery (if is that possible of course), because I'm not familiar with that library.
HTML:
<form name="checkBox">
<input onchange="checkbox()" type="checkbox" class="cbox" />
</form>
JS:
function checkbox(){
var checkbox = document.getElementByClass('cbox');
if(document.getElementById('cbox').checked === true){
checkbox.style.background = "url('uncheck.png')";
}else{
checkbox.style.background = "url('check.png')";
}
}

You are mixing class names and ID's. Try this.
HTML:
<form name="checkBox">
<input onchange="checkbox()" type="checkbox" id="cbox" />
</form>
JS:
function checkbox(){
var checkbox = document.getElementById('cbox');
if(checkbox.checked === true){
checkbox.style.background = "url('uncheck.png')";
}else{
checkbox.style.background = "url('check.png')";
}
}

How about a pure CSS solution without any need to use images: http://jsfiddle.net/7qcE9/1/.
HTML:
<form name="checkBox">
<input type="checkbox" id = "checkbox1" />
<label for = "checkbox1"></label>
</form>
CSS:
form > input[type = "checkbox"] {
display: none;
}
form > label {
display: inline-block;
width: 20px;
height: 20px;
border: 1px solid #000;
border-radius: 3px;
font-size: 20px;
text-align: center;
cursor: pointer;
}
form > input[type = "checkbox"]:checked + label:before {
content:'\2714';
}

You can pass a reference to the checkbox using this in the inline handler as follows:
html
<form name="checkBox">
<input onchange="checkbox(this)" type="checkbox" class="cbox" />
</form>
js
function checkbox(elm){ // elm now refers to the checkbox
if(elm.checked === true){
elm.style.background = "url('uncheck.png')";
}else{
elm.style.background = "url('check.png')";
}
}
So that you can use the function for n number of elements.

Related

Using eventlistener to disable and enable a button

I have a chess form with six fields. Two are drop down menus to select names (whiteplayername and blackplayername) and the other four can be used to add a custom name instead (firstnamewhite, lastnamewhite, firstnameblack, lastnameblack). Currently, I want my javascript to disable the custom fields if a name has been selected from the drop down menu (this is working). I also want the submit button to be disabled if neither the whiteplayername or firstnamewhite and blackplayername of firstnameblack is selected. Currently, the submit-button becomes enabled if a name is selected from both the blackplayername and whiteplayname menus but then does not become disabled again if an empty field is selected in either.
Edit
The full html is below, though I have taken out a section just made up of text and rows from the table in order to cut down on the space used.
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>chessopenings3</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<style>
body {
style: "background-color: #FF0000;
}
.topnav {
position: relative;
overflow: hidden;
background-color: #333;
border: 2px;
width: max-content;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
border: 2px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
border: 2px;
}
.formformat {
color: white;
padding: 50px;
font-size: 24px;
font-family: Arial, Helvetica, sans-serif;
}
.instructions-text {
position: absolute;
color: white;
align: center;
left: 750px;
top: 150px;
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
.warning {
position: absolute;
color: white;
text-align: left;
left: 150px;
top: 50px;
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
select {
width: 120px;
}
select:focus {
min-width: 120px;
width: auto;
}
#media screen and (max-width: 500px) {
.navbar a {
float: none;
display: block;
}
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function () {
let isformvalid = false;
document.getElementById("submit-button").disabled = !isformvalid;
document.getElementById("whiteplayername").addEventListener("change", function () {
let blackplayername =
document.getElementById("blackplayername");
let firstnameblack =
document.getElementById("firstnameblack");
let firstnamewhite =
document.getElementById("firstnamewhite");
let lastnamewhite =
document.getElementById("lastnamewhite");
let lastnameblack =
document.getElementById("lastnameblack");
disablewhenmandatorynamemissingwhitename(this.value, blackplayername, firstnameblack, firstnamewhite, lastnameblack, lastnamewhite);
isformvalid = checkeitherfirstorfullnamepopulated (this.value, firstnamewhite, blackplayername, firstnameblack, isformvalid);
document.getElementById("submit-button").disabled = !isformvalid;
});
});
function disablewhenmandatorynamemissingwhitename(whiteplayername, blackplayername, firstnameblack, firstnamewhite, lastnameblack, lastnamewhite) {
if (whiteplayername !== "") {
firstnamewhite.disabled = true;
lastnamewhite.disabled = true;
} else {
firstnamewhite.disabled = false;
lastnamewhite.disabled = false;
}
}
function disablewhenmandatorynamemissingblackname(whiteplayername, blackplayername, firstnameblack, firstnamewhite, lastnameblack, lastnamewhite) {
if (blackplayername !== "") {
firstnameblack.disabled = true;
lastnameblack.disabled = true;
} else {
firstnameblack.disabled = false;
lastnameblack.disabled = false;
}
};
function checkeitherfirstorfullnamepopulated(whiteplayername, firstnamewhite, blackplayername, firstnameblack, isformvalid) {
if ((whiteplayername === "" || whiteplayername === null) && (firstnamewhite.trim() === "")) {
return false;
}
else if ((blackplayername === "" || blackplayername === null) && (firstnameblack.trim() === "")) {
return false;
}
return true;
};
</script>
<body style="background-color:rgb(68, 57, 57);">
<div class="warning">
<p id="warningtext"></p><br>
</div>
<div class="topnav">
<a th:href="#{main.html}"><i class="material-icons"
style="border:2px;font-size:60px;color:rgb(0, 0, 0);">arrow_back</i></a>
</div>
<div class="formformat">
<form th:object="${game}" th:action="#{/addgame}" th:method="post">
<label for="whiteplayername">Select white player:</label>
<select name="whiteplayername" id="whiteplayername" th:object="${names}" th:field="${game.whitePlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<th:block th:each="name : ${names}">
<option th:value="${name.name}"
th:text="${name.name}"></option>
</th:block>
</select>
<label for="blackplayername">Select black player:</label>
<select name="blackplayername" id="blackplayername" th:object="${names}" th:field="${game.blackPlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<th:block th:each="name : ${names}">
<option th:value="${name.name}"
th:text="${name.name}"></option>
</th:block>
</select><br><br>
<label for="firstnamewhite">First name white:</label>
<input type="text" id="firstnamewhite" th:field="*{firstNameWhite}"/>
<label for="firstnameblack">First name black:</label>
<input type="text" id="firstnameblack" th:field="*{firstNameBlack}"/><br><br>
<label for="lastnamewhite">Last name white:</label>
<input type="text" id="lastnamewhite" th:field="*{lastNameWhite}"/>
<label for="lastnameblack">Last name black:</label>
<input type="text" id="lastnameblack" th:field="*{lastNameBlack}"/><br><br>
<label for="date">Date:</label><br>
<input type="date" id="date" th:field="*{date}">
<table>
<tr>
<th>Move</th>
<th>White</th>
<th>Black</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" id="white1" th:field="*{moves}"></td>
<td><input type="text" id="black1" th:field="*{moves}"></td>
</tr>
</table>
<input type="submit" value="Submit" id="submit-button">
</form>
</div>
<br><br>
</body>
</html>
Here's a solution that should meet all your requirements:
<script type="module">
const form = document.getElementById("form");
const submitButton = document.getElementById("submitbutton");
const whitePlayerName = document.getElementById("whiteplayername");
const blackPlayerName = document.getElementById("blackplayername");
const firstNameBlack = document.getElementById("firstnameblack");
const firstNameWhite = document.getElementById("firstnamewhite");
const lastNameWhite = document.getElementById("lastnamewhite");
const lastNameBlack = document.getElementById("lastnameblack");
form.addEventListener('change', () => {
const whiteNameSelected = whitePlayerName.value;
// Disable white name inputs if white name is selected in the dropdown
firstNameWhite.disabled = whiteNameSelected;
lastNameWhite.disabled = whiteNameSelected;
// Determine if the white name is either selected or typed in the inputs
const validWhiteName = whiteNameSelected || (firstNameWhite.value && lastNameWhite.value);
const blackNameSelected = blackPlayerName.value;
// Disable black name inputs if black name is selected in the dropdown
firstNameBlack.disabled = blackNameSelected;
lastNameBlack.disabled = blackNameSelected;
// Determine if the black name is either selected or typed in the inputs
const validBlackName = blackNameSelected || (firstNameBlack.value && lastNameBlack.value);
const submitAvailable = validWhiteName && validBlackName;
submitButton.disabled = !submitAvailable;
});
</script>
<form th:object="${game}" th:action="#{/addgame}" th:method="post" id="form">
<label for="whiteplayername">Select white player:</label>
<select name="whiteplayername" id="whiteplayername" th:object="${names}" th:field="${game.whitePlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<option value="name1">Name 1</option>
<option value="name2">Name 2</option>
</select>
<label for="blackplayername">Select black player:</label>
<select name="blackplayername" id="blackplayername" th:object="${names}" th:field="${game.blackPlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<option value="name1">Name 1</option>
<option value="name2">Name 2</option>
</select><br><br>
<label for="firstnamewhite">First name white:</label>
<input type="text" id="firstnamewhite" th:field="*{firstNameWhite}"/>
<label for="firstnameblack">First name black:</label>
<input type="text" id="firstnameblack" th:field="*{firstNameBlack}"/><br><br>
<label for="lastnamewhite">Last name white:</label>
<input type="text" id="lastnamewhite" th:field="*{lastNameWhite}"/>
<label for="lastnameblack">Last name black:</label>
<input type="text" id="lastnameblack" th:field="*{lastNameBlack}"/><br><br>
<label for="date">Date:</label><br>
<input type="date" id="date" th:field="*{date}">
<button id="submitbutton" disabled>Submit</button>
</form>
It works by combining all the logic into a single handler for the entire form change. Then, if a name is selected in the dropdown, it disables the custom name fields, if not, it leaves them enabled. The code checks to make sure both white and black name are valid and depending on that sets the submit button enabled/disabled state.
You didn't post your whole HTML so I added the button by hand and also your selects are populated dynamically so I had to hardcode some options in them. Please, for Stack Overflow questions, always post examples reproducible by other people to aid them in helping you.
Can you provide the html code too? I also recommend to name properly ur variables and fucntions beacuase are pretty illegibles by the way. Try to type the first letter of each word that compunds the varibale in uppercase at least.
Instead of:
let firstnameblack
Do:
let firstNameBlack
I also recommend to put 2 or 3 letters according to what specifies this varibale, for example if it's a button, do:
let btnFirstNameBlack
Anyways if you can provide the html code maybe I can help you with the button issue.

I have created a form using HTML and Javascript, I want to display the specific dialogue based on numeber of selection. But alert does not work here

The idea is for the user to select the options and the best employment
sector would be suggested by the form based on his selection.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>
Survey that will will give you suggestion.
</title>
<style>
/* Styling the Body element i.e. Color,
Font, Alignment */
body {
background-color: #05c46b;
font-family: Verdana;
text-align: center;
}
/* Styling the Form (Color, Padding, Shadow) */
form {
background-color: #fff;
max-width: 500px;
margin: 50px auto;
padding: 30px 20px;
box-shadow: 2px 5px 10px rgba(0, 0, 0, 0.5);
}
/* Styling form-control Class */
.form-control {
text-align: left;
margin-bottom: 25px;
}
/* Styling form-control Label */
.form-control label {
display: block;
margin-bottom: 10px;
}
/* Styling form-control input,
select, textarea */
.form-control input,
.form-control select,
.form-control textarea {
border: 1px solid #777;
border-radius: 2px;
font-family: inherit;
padding: 10px;
display: block;
width: 95%;
}
/* Styling form-control Radio
button and Checkbox */
.form-control input[type="radio"],
.form-control input[type="checkbox"] {
display: inline-block;
width: auto;
}
/* Styling Button */
button {
background-color: #05c46b;
border: 1px solid #777;
border-radius: 2px;
font-family: inherit;
font-size: 21px;
display: block;
width: 100%;
margin-top: 50px;
margin-bottom: 20px;
}
</style>
</head>
The form is made with HTML. and for javascript operations i have added
value=1 in the checkbox for generating the different output string.
please view the code below to understand better.
<body>
<h1>Your job type survey suggestion quiz</h1>
<!-- Create Form -->
<form id="form">
<!-- Details -->
<div class="form-control">
<label for="name" id="label-name">
Name
</label>
<!-- Input Type Text -->
<input type="text"
id="name"
placeholder="Enter your name" />
</div>
<div class="form-control">
<label for="email" id="label-email">
Email
</label>
<!-- Input Type Email-->
<input type="email"
id="email"
placeholder="Enter your email" />
</div>
<div class="form-control">
<label for="age" id="label-age">
Age
</label>
<!-- Input Type Text -->
<input type="text"
id="age"
placeholder="Enter your age" />
</div>
<div class="form-control">
<label for="role" id="label-role">
Which option best describes you?
</label>
<!-- Dropdown options -->
<select name="role" id="role">
<option value="student">Student</option>
<option value="intern">Intern</option>
<option value="professional">
Professional
</option>
<option value="other">Other</option>
</select>
</div>
<div class="form-control">
<label>
DO you like studying?
</label>
<!-- Input Type Radio Button -->
<label for="recommed-1">
<input type="radio"
id="recommed-1"
name="recommed">Yes</input>
</label>
<label for="recommed-2">
<input type="radio"
id="recommed-2"
name="recommed">No</input>
</label>
<label for="recommed-3">
<input type="radio"
id="recommed-3"
name="recommed">Maybe</input>
</label>
</div>
<div class="form-control">
<label>Skills that you have
<small>(Check all that apply)</small>
</label>
<!-- Input Type Checkbox -->
<label for="inp-1">
<input type="checkbox" name="inp" id="c" value=1>Coding</input></label>
<label for="inp-2">
<input type="checkbox" name="inp" id="d" value=2>Dancing</input></label>
</div>
<button onclick="checkCheckbox()">
Submit
</button>
</form>
Here as of now only 2 questions are in the form, I want to add more
questions and on based of the selection the form will suggest. In this
the alert or any message i`enter code here`s not shown neither there is any error.
<script>
function checkCheckbox() {
var c = document.getElementById("c");
var d = document.getElementById("d");
var add=0
if (c.checked == true){
var y = document.getElementById("c").value;
var add=y;
return add;
}
else if (d.checked == true){
var n = document.getElementById("d").value;
var add += n;
}
else {
return document.getElementById("error").innerHTML = "*Please mark any of checkbox";
}
if(add==2){
alert('You are multi-talented! become a dancer or a coder');
}
else{
alert('Become a coder');
</script>
</body>
</html>
here on selecting dancing and coding a different output should be
given and on selecting either dancing or either coding a different
output string should be shown. please suggest for any modifications or
if there is a better way to complete this idea.
There are several errors in the script section. You can use Web Developer debugging in your browser to check them out. I can see that you are new to coding in general, so there are a couple of common mistakes we've all made in the beginning.
This is one way of writing the function so it works as I think you intended it:
function checkCheckbox() {
var c = document.getElementById("c");
var d = document.getElementById("d");
var add = 0, val;
if (c.checked == true){
val = "coder";
add += 1;
}
if (d.checked == true){
val = "dancer";
add += 1;
}
if (add == 2) {
alert('You are multi-talented! become a dancer or a coder');
return true;
}
else if (add == 1) {
alert('Become a ' + val);
return true;
}
else {
document.getElementById("error").innerHTML = "*Please mark any of checkbox";
return false;
}
}
Also, you need to add return in the event handler of the button, to avoid it submitting when the form is invalid:
<button onclick="return checkCheckbox()">Submit</button>
And lastly add an element for the error message that is referred to in the script. Something like:
<div id="error"></div>

Make Anchor tag work conditionally using Javascript

I have a Radio button. I want to implement a validation on "Submit" Anchor tag that displays an error if no selection is made on the radio button and redirects to the URL provided in the href attribute if the radio button selection is made.
Below is the code for radio button -
<div>
<input required="" type="radio" id="group02-0" name="group02" value="Yes" onclick="yesnoCheck();">
<label for="group02-0" >Yes</label>
<input type="radio" id="group02-1" name="group02" value="No" onclick="yesnoCheck();">
<label for="group02-1">No</label>
</div>
<script>
var radio_value = "";
function yesnoCheck() {
radio_value = document.querySelector('input[name="group02"]:checked').value;
}
</script>
In the same HTML file, I have code for the Submit Anchor tag -
<span>Submit</span>
<script>
function submitCheck() {
if (radio_value === "") {
//Display an error. The user should not be taken to the next page
return false;
} else {
//User should be taken to the URL in the href attribute
return true;
}
}
</script>
Irrespective of whether I make a selection on the radio button, the anchor tag always takes me to the next page. Please help!
You don't need two radio buttons. Only one Checkbox.
Use Event.preventDefault() to prevent default browser navigation
Use the input element's checked state to determine the outcome
Finally use document.location to navigate to a EL_submitBtn.getAttribute('href')
PS: Don't use inline JavaScript (in HTML). JS should be in one place and that's your JS file or inside a <script> tag. It's easier to debug and maintain.
Single checkbox
const EL_submitBtn = document.querySelector('#submitBtn');
const EL_acceptCkb = document.querySelector('[name="accept"]');
function submitCheck(ev) {
ev.preventDefault(); // prevent follow link
if (!EL_acceptCkb.checked) { // Unchecked
alert("You will not get a better UX");
} else { // Checked
alert("Yes! Buckle up!")
document.location = EL_submitBtn.getAttribute('href');
}
}
EL_submitBtn.addEventListener('click', submitCheck);
<div>
<h3>Would you like a better UX?</h3>
<label>
<input type="checkbox" name="accept"> Yes I do
</label>
</div>
<a id="submitBtn" href="https://www.google.com">Submit</a>
Two radio buttons
Use document.querySelector('[name="accept"]:checked') to get the checked one, if any.
const EL_submitBtn = document.querySelector('#submitBtn');
function submitCheck(ev) {
ev.preventDefault(); // prevent follow link
const EL_acceptCkd = document.querySelector('[name="accept"]:checked');
if (!EL_acceptCkd) { // None checked
alert("You must select Yes or No.");
} else if (EL_acceptCkd.value === 'no') { // "NO" checked
alert("You will not get a better UX");
} else { // "YES" checked
alert("Yes! Buckle up!")
document.location = EL_submitBtn.getAttribute('href');
}
}
EL_submitBtn.addEventListener('click', submitCheck);
<div>
<h3>Would you like a better UX?</h3>
<label>
<input type="radio" name="accept" value="yes"> Yes
</label>
<label>
<input type="radio" name="accept" value="no"> No
</label>
</div>
<a id="submitBtn" href="https://www.google.com">Submit</a>
use css pointer-events: none; -> https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
If you absolutely want to use button radios (even if it's a bit twisted as an idea) here is the code:
const aHrefGoogle = document.getElementById('aHrefGoogle');
document.querySelectorAll('input[name=group02]').forEach(el=>
{
el.onchange=_=>{ if (el.checked) setLinkOnOff(el.value) }
})
function setLinkOnOff(val)
{
if (val==='yes') { aHrefGoogle.classList.remove('adisableHref') }
else { aHrefGoogle.classList.add('adisableHref') }
}
.adisableHref {
color: grey;
pointer-events: none;
cursor: default;
text-decoration-line: none;
}
make link Google active ?
<label ><input type="radio" name="group02" value="yes">Yes </label>
<label ><input type="radio" name="group02" value="no" checked>No! </label>
<br><br>
<span> Google </span>
for memo here is the initial code with a checkbox :
const yesnoCheck = document.getElementById('yesnoCheck')
, aHrefGoogle = document.getElementById('aHrefGoogle')
;
// init
yesnoCheck.checked = false
aHrefGoogle.classList.add('adisableHref')
yesnoCheck.oninput =_=>
{
if (yesnoCheck.checked) { aHrefGoogle.classList.remove('adisableHref') }
else { aHrefGoogle.classList.add('adisableHref') }
}
#yesnoCheck { display: none; }
#yesnoCheck + label { display: inline-block; background: #cd3c3c; color: white; padding: .17em .2em; cursor: pointer; }
#yesnoCheck:checked + label { background: #378b2c; }
#yesnoCheck + label::before { content: 'NO'; display: inline-block; width:2.6em; text-align: center; }
#yesnoCheck + label::after { content: ''; display: inline-block; width:0; text-align: center; }
#yesnoCheck:checked + label::before { content: ''; width:0; }
#yesnoCheck:checked + label::after { content: 'YES'; width:2.6em; }
.adisableHref {
color: grey;
pointer-events: none;
cursor: default;
text-decoration-line: none;
}
make link Google active ?
<input type="checkbox" id="yesnoCheck"><label for="yesnoCheck">▉</label>
<br><br>
<span> Google </span>

How to make an input field readonly based on anther input field?

I am making a unit converter with two input fields, one for centimeters and the other for inches. I was wondering if it would be possible for one of the fields to be changed to read only if there is input in the other field. Here is my code for one of the fields:
<input name="cm" class="inputs peach Calibri" type="number" min="0" step="1" />.
Any help would be appreciated. Thanks!
This would be a fairly good starting point.
let cmInput = document.getElementById("cminput");
let inInput = document.getElementById("inchinput");
cmInput.onkeyup = function(){
if(cmInput.value !== ""){
inInput.disabled = true;
}else{
inInput.disabled = false;
}
};
inInput.onkeyup = function(){
if(inInput.value !== ""){
cmInput.disabled = true;
}else{
cmInput.disabled = false;
}
};
<input type="text" placeholder="centimetres" id="cminput">
<input type="text" placeholder="inches" id="inchinput">
Not the cleanest way but it works just add your logic for conversion. This also remove readonly attr when input field is empty
jsfiddle (click me)
<label for="cm">cm: </label>
<input name="cm" id="cm" class="inputs peach Calibri" type="number" min="0" step="1" />
<label for="inch">inch: </label>
<input name="inch" id="inch" class="inputs peach Calibri" type="number" min="0" step="1" />
$('#cm').on('keyup', function() {
if ($('#cm').val() != '') {
$('#inch').prop('readonly', true);
} else if ($('#cm').val() == '') {
$('#inch').prop('readonly', false);
}
});
$('#inch').on('keyup', function() {
if ($('#inch').val() != '') {
$('#cm').prop('readonly', true);
} else if ($('#inch').val() == '') {
$('#cm').prop('readonly', false);
}
});
would you consider another pattern for this?
The readonly solution is pretty straigh forward, but a lot of sites with not only numeric convertion, for example, google translate, use a button to switch the convertion leaving the right side of the converter control with a read only, so if you want to make something like this in order to follow a more standart pattern
here it is
$('button').on('click',function(){
$('.cont').toggleClass('invert')
});
$('input').on('keypress',function(){
if($('.cont').hasClass('invert')){
// some convertion code for INCH to CM
}else{
// some convertion code for CM to INCH
}
});
.cont{
display:flex;
align-items: center;
justify-content: center;
border:1px solid silver;
}
.cont.invert{
flex-direction: row-reverse;
}
fieldset{
border:none;
position:relative;
}
button{
display: block;
line-height: 22px;
}
.cont.invert fieldset:first-child:after{
content:"";
display: block;
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top:0px;
background-color: rgba(255,255,255,.3);
}
.cont.invert fieldset:last-child:after{
display: none;
}
.cont fieldset:last-child:after{
content:"";
display: block;
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top:0px;
background-color: rgba(255,255,255,.3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont">
<fieldset>
<label for="inp1">CM</label>
<br>
<input type="text">
</fieldset>
<button>
< >
</button>
<fieldset>
<label for="inp1">INCH</label>
<br>
<input type="text">
</fieldset>
</div>
As you can see, i did not disabled the input, i used a block to cover it from editing, the block on top of the right input has a white background with alpha on it, this way, if you want, you can control the way of the "disabled" one, no touching the input´s css and may looks the same on every browser.
Hope this helps
You could call a js function oninput like so:
<input type="text" id="cm" oninput="input('cm')"/>
<input type="text" id="inch" oninput="input('inch)"/>
function input(which){
if(which === 'cm'){
if(document.getElementById('cm').value!= ''){
document.getElementById('inch').disabled = true;
}else{
document.getElementById('cm').disabled = false;
}
}else{
if(document.getElementById('inch').value!= ''){
document.getElementById('cm').disabled = true;
}else{
document.getElementById('inch').disabled = false;
}
}
}

Is it possible to take more than one input from a textbox in a php form?

I am trying to make a calculator program in php code.
I made it using html and javascript, but I've been told to use php code for the logical part.
Is there any way we can take more than one input from a textbox, in a php form ?
Yes, you can easily use multiple inputs in a form, by giving them different names and accessing them through $_REQUEST['input_name'].
In this example, what I am doing is taking the selected checkboxes from the popup and putting them into the text input field in the main form as a comma-separated list.
HTML
<input type="text" id="entry-r1" placeholder="place" tabindex="1">
<a class="show-lookup button" href="#" id="popup-r1" tabindex="2"><i class="fa fa-search"></i></a>
<div class="overlay"> </div>
<div class="lookup-multiselect" id="lookup-r1">
<a class="button close-button right">x</a>
<form action="" id="form-r1" name="form-r1" method="post">
<input class="checkall" id="checkall" type="checkbox">
<label for="checkall" class="narrow">Select all</label>
<p class="category" id="checkboxes-r1"><strong>Select...</strong><br>
<input class="js-popup-focus" type="checkbox" name="place" id="antwerp" value="Antwerp" tabindex="3"> <label for="antwerp">Antwerp</label><br>
<input type="checkbox" name="place" id="berlin" value="Berlin" tabindex="3"> <label for="berlin">Berlin</label><br>
<input type="checkbox" name="place" id="cairo" value="Cairo" tabindex="3"> <label for="cairo">Cairo</label><br>
<input type="checkbox" name="place" id="duss" value="Düsseldorf" tabindex="3"> <label for="duss">Düsseldorf</label><br>
</p>
</form>
Use selected
</div>
CSS
.overlay {
display: none;
position: fixed;
text-align: center;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
opacity: 0.7;
background: #333;
}
.lookup-popup, .lookup-multiselect {
padding: 0.5em;
display: none;
z-index: 99999;
background-color: #fff;
position: absolute;
top: 5em;
left: 25%;
width: 20%;
}
jQuery
$(document).ready(function ()
{
/* get id of form to work with */
$('.show-lookup').click(function()
{
var pairedId = $(this).attr('id').split('-');
var lookupToDisplay = '#lookup-' + pairedId[1];
$('.overlay').show();
$(lookupToDisplay).show();
$('.js-popup-focus').focus();
});
/* put value selected in lookup into field in main form */
$('.lookup-popup input').on('change', function()
{
var fieldname = $(this).attr('name');
var pairedId = $(this).parent().attr('id').split('-');
var selOption = $('input[name='+fieldname+']:checked').val();
$("#entry-"+pairedId[1]).val(selOption);
});
/* for checkbox version, append selected values to field in main form */
$('.lookup-multiselect input').on('change', function()
{
var pairedId = $(this).parent().attr('id').split('-');
//event.preventDefault();
var selOptions = $(".category input:checkbox:checked").map(function(){
return $(this).val();
}).get(); // <----
//console.log(selOptions);
var selectedString = selOptions.toString();
$("#entry-"+pairedId[1]).val(selOptions);
});
$('.close-button').click(function()
{
$(this).parent().hide();
var pairedId = $(this).parent().attr('id').split('-');
$('.overlay').hide();
$("#entry-"+pairedId[1]).focus();
});
});

Categories