I have a <div> with checkbox and button inside and wanna put field between them, but the field is always leftmost. I tried to use text instead of filed and that worked, but filed doesn't want to obey to my CSS rules.
Also, I need to position all of those using JavaScript.
var list = document.getElementById("list");
var item = document.createElement("div");
item.className="item";
list.appendChild(item);
var itemsField = document.createElement("input");
itemsField.setAttribute('type', 'input');
itemsField.className = '.itemsField';
item.appendChild(itemsField);
var taken = document.createElement("input");
...
item.appendChild(taken);
...
item.appendChild(del);
Some CSS rules:
.itemsField {
display: inline-block;
float:center;
margin-left:1%;
}
checkbox {
display: inline-block;
float:left;
width:auto;
}
I think the reason why the css classes don't obey the rules is due to your script. So try changing
itemsField.className = '.itemsField';
to
itemsField.className = 'itemsField';
Besides, I don't think that there is a "center" value for the "float" property ...
.itemsField {
display: inline-block;
float:center;
margin-left:1%;
}
If you want to center something, use text-align : center instead. Hope this help.
You can use string literals. The other issue is the use of class name as .itemsField, you need to remove the dot. In your code you are appending the div with innerText X at the last
var list = document.getElementById("list");
let innerDOM = `<div>
<input type = 'input' class ='itemsField'><span>X</span><input type ='checkbox' name ='taken'>
</div>`;
list.innerHTML = innerDOM;
.itemsField {
display: inline-block;
float: center;
margin-left: 1%;
}
checkbox {
display: inline-block;
float: left;
width: auto;
}
<div id='list'></div>
float: center doesn't exist.
Above answers are pretty clear.
But if you need a very simple answer, use this.
<center>
<input type="checkbox"> <input type="textarea"> <input type="submit" value="Submit"><br>
</center>
if you want to move the whole thing into a specific position or style, use tag.
Related
N.B.: I should note that the proper solution to this is to just use the 'placeholder' attribute of an input, but the question still stands.
Another N.B.: Since, as Quentin explains below, the "value" attribute stores the default value, and the input.value IDL attribute stores the current value, the JavaScript I used to "fix" the problem in my below example is non-conforming, as it uses the (non-IDL) value attribute to store current, rather than default, values. Besides, it involves DOM access on every key press, so it was always just a flawed demo of the problem I was having. It's actually quite terrible code and shouldn't be used ever.
CSS selectors made me think that I could make an input with a label that acts as a preview without any JS. I absolutely position the input at 0,0 inside the label (which is displayed as an inline-block) and give it a background of "none", but only if it's got a value of "" and isn't focussed, otherwise it has a background colour, which obscures the label text.
The HTML5 spec says that input.value reflects the current value of an input, but even though input.value updates as you type into an input, CSS using the input[value=somestring] selector applies based only on what was explicitly typed into the document, or set in the DOM by the JavaScript setAttribute method (and perhaps by other DOM-altering means).
I made a jsFiddle representing this.
Just in case that is down, here is an HTML document containing the relevant code:
<!doctype html>
<head>
<meta charset="utf-8" />
<title>The CSS Attribute selector behaves all funny</title>
<style>
label {
display: inline-block;
height: 25px;
line-height: 25px;
position: relative;
text-indent: 5px;
min-width: 120px;
}
label input[value=""] {
background: none;
}
label input, label input:focus {
background: #fff;
border: 1px solid #666;
height: 23px;
left: 0px;
padding: 0px;
position: absolute;
text-indent: 5px;
width: 100%;
}
</style>
</head>
<body>
<form method="post">
<p><label>name <input required value=""></label></p>
</form>
<p><button id="js-fixThis">JS PLEASE MAKE IT BETTER</button></p>
<script>
var inputs = document.getElementsByTagName('input');
var jsFixOn = false;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].parentNode.tagName == 'LABEL') { //only inputs inside a label counts as preview inputs according to my CSS
var input = inputs[i];
inputs[i].onkeyup= function () {
if (jsFixOn) input.setAttribute('value', input.value);
};
}
}
document.getElementById('js-fixThis').onclick = function () {
if (jsFixOn) {
this.innerHTML = 'JS PLEASE MAKE IT BETTER';
jsFixOn = false;
} else {
this.innerHTML = 'No, actually, break it again for a moment.';
jsFixOn = true;
}
};
</script>
</body>
</html>
I could be missing something, but I don't know what.
The value attribute sets the default value for the field.
The value property sets the current value for the field. Typing in the field also sets the current value.
Updating the current value does not change the value attribute.
Attribute selectors only match on attribute values.
There are new pseudo classes for matching a number of properties of an input element
:valid
:invalid
:in-range
:out-of-range
:required
A required element with no value set to it will match against :invalid. If you insist on using the value instead of placeholder, you could simply add a pattern or a customValidity function to force your initial value to be counted as invalid.
I am building an "autofill" function. When the user types something in an input field and the system finds this string in the database it should display the string into the input field in grey, similar to what google used to/still have/has.
Therefore I built two input fields, one that's clearly visible:
html:
<input id="email_input" type="text">
<input id="autofill" type="text">
css:
#email_input{
background-color: transparent;
z-index: 100;
}
Then I position the autofill input via JS exactly where email_input is.
function positionAutocompleteInput(){
var top = $('#email_input').position().top;
var left = $('#email_input').position().left;
$('#autofill').css({'top':top});
$('#autofill').css({'left':left});
}
positionAutoFillInput();
The actual autfill I do like this:
function autofill(context){
var input = $('#email_input').val();
var replacement = context[0].email;
replacement = replacement.slice(input.length);
var display = input + replacement;
$('#autofill').val(display)
}
I tried calling positionAutoFillInput(); onInput, so that it gets repositioned with each input. If I look at the positions of both input fields in the console, they both have the same positions.
Both input fields have the same font-size and font-family.
For some reason it still looks off:
Anyone know an answer?
Can you just position them with CSS like this? This way it requires no JavaScript to position it.
#autofill, #email_input {
font-size: 20px;
}
#autofill {
position: absolute;
color: #CCCCCC;
}
#email_input {
position: relative;
z-index: 1;
background: transparent;
}
<h1>Test</h1>
<div>
<input id="autofill" type="text" value="1234567890">
<input id="email_input" type="text">
</div>
I wrote a script to check checkbox when I am clicking on it's respective image.
Image have id like checkbox-img-1 and checkbox input have id like checkbox-1 for 1st pair of checkbox and image. For 2nd pair id's are checkbox-img-2 and checkbox-2 and so on.
So, whenever I click on image I want to check the respective checkbox. For few images the UI is getting updated but for few images it's not getting updated.
What is the possible problem? I searched a bit but all questions were doing mistake of having attr in place of prop.
My script is in pure javascript. I tried with jQuery but I am getting same bug.
I figured out that content which is not present or not yet displayed in front are not getting selected.
The javascript code is:
/* Check option on image click */
$(".option-check-img").click(function () {
var checkbox_img_id = $(this).attr("id");
var checkbox_id = checkbox_img_id.replace("checkbox-img", "checkbox");
if(document.getElementById(checkbox_id).checked)
{
document.getElementById(checkbox_id).checked = false;
var d = document.getElementById(checkbox_img_id);
d.className = "img-circle pointer";
/*$("#checkbox_id").prop("checked", false);
$("#checkbox_img_id").removeClass("img-border");
console.log(document.getElementById(checkbox_id));*/
}
else
{
document.getElementById(checkbox_id).checked = true;
var d = document.getElementById(checkbox_img_id);
d.className += " img-border";
/*$("#checkbox_id").prop("checked", true);
$("#checkbox_img_id").addClass("img-border");
console.log(document.getElementById(checkbox_id));*/
}
});
Any solution? Thank you.
Try to use prop() instead of attr()
JQuery Script not checking check-boxes correctly
Read docs for more info jQuery prop().
Are you sure you want to use js for this? You can do this just with css.
*, *:before, *:after {
font-family: sans-serif;
box-sizing: border-box;
}
label {
display: block;
margin-bottom: 20px;
cursor: pointer;
}
span:before {
content: '';
display: inline-block;
width: 15px;
height: 15px;
margin-right: 10px;
background: white; /* you can place your image url here */
border: 4px solid white;
border-radius: 3px;
box-shadow: 0 0 0 1px black;
}
input {
display: none;
}
input:checked + span:before {
background: black;
}
<label>
<input type="checkbox">
<span>Checkbox 1</span>
</label>
<label>
<input type="checkbox">
<span>Checkbox 2</span>
</label>
There is a pure-html solution (Fiddle):
<ul><li>
<input type="checkbox" id="checkbox-1" />
<label for="checkbox-1"><img /></label>
</li>
<li>
<input type="checkbox" id="checkbox-2" />
<label for="checkbox-2"><img /></label>
</li></ul>
if you need to add styling to your images when checkbox is checked you can use css3 (Fiddle):
input:checked + label img{
border: 1px solid black;
}
input:not(:checked) + label img{
border: 1px solid green;
}
// If you want to hide the checkbox
input[type=checkbox] {
display: none;
}
You should build your html such the checkbox and the image are next to each other.
This approach is much more elegant and doesn't use unnecessary javascript.
$(".option-check-img").click(function() {
var $this = $(this);
var checkbox_img_id = $(this).attr("id");
var checkbox_id = checkbox_img_id.replace("checkbox-img", "checkbox");
if ($("#" + checkbox_id + ":checked").length) {
$("#" + checkbox_id).prop('checked', false);
$("#" + checkbox_img_id).removeClass("img-border");
$("#" + checkbox_img_id).addClass("img-circle pointer");
} else {
$("#" + checkbox_id).prop('checked', true);
$("#" + checkbox_img_id).removeClass("img-circle pointer");
$("#" + checkbox_img_id).addClass("img-border");
}
});
Converted your code to proper jQuery Code.
Assumption: ID is of your check-box element.
Make sure no elements have same ID in your DOM.
Updated code to remove alternate-classes too.
Thanks
your checkbox id's are not unique.
A different checkbox with the same id is getting checked / unchecked instead of the one you want to manupulate. getElementById / $('#id') will return only one element which ever it finds first.
for instance, in the link that you shared the option Party has a id of checkbox-24 but with the same id there are total of three checkboxes.
similarly for Music with a id of checkbox-27 there are again 3 instances of checkbox with that id.
Your script is correct, but the ids are not unique. Make the id's unique or use someother identifier or combination of identifiers to uniquely identify the checkbox which you want to manipulate.
the problem was with infinite loop. Without infinite loop its working. But still I want that infinite slider so I will try something different.
I have a JavaScript function that displays text based on input in a text field. When a value is entered into the text field, my program will check to see if the value is correct. If it is correct, my program displays, "You are correct!" and if it is incorrect, my program displays, "Try again!"
The text field and button are both centered horizontally on the page, but I cannot figure out how to center the "You are correct!" and "Try again!"
I feel like I have tried everything, but obviously I haven't, considering I can't get it to work.
Here is the code for my JavaScript function:
<center><p>Can you remember how many books I listed at the bottom of the page?</p></center>
<center><input id="numb"></center>
<center><button type="button" onclick="myFunction()">Submit</button></center>
<p id="demo"></p>
<div class="jsFunction">
<script>
function myFunction()
{
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;
// If x is Not a Number or less than five or greater than five
if (isNaN(x) || x < 5 || x > 5)
{
text = "Try again!";
}
else
{
text = "You are correct!";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</div>
Here is the CSS code for the function:
.jsFunction
{
margin-left: auto;
margin-right: auto;
}
This specific CSS code is only one of many, many attempts I have made at centering the text in the function.
Here is a link to a picture that will show you the problem I am having:
http://i.stack.imgur.com/Hb01j.png
Please help!
Try setting a class on the p tag that contains text-align: center;
Edit
Nesting your script in a div is meaningless as script tags don't get rendered
You can either target #demo in your css (for the text alignment) or add a class align-center that contains the correct style.
I would recommend the latter as the becomes more reusable, whereas you can't reuse an id on the same page
The fact that you are using JavaScript isn't important to this question. I mention it because of the title "How to Center Text in a JavaScript Function" and your attempt to center the actual script element containing your JavaScript code.
You want to center the contents of an element that happens to be controlled by JavaScript, but the answer is CSS-only.
As Ryuu's answer mentions, text-align: center will do the job for (you guessed it) text and other inline-level content.
You should not use the deprecated center tag.
Your attempt to use margins will center something if you apply it to the correct element and the element has a width. That "something" is the element, however, not the contents of the element.
In other words, margin can be used to align the box, not the stuff within the box.
Example 1: centers the element, but the text is still left-aligned.
Example 2: centers the element and its inline-level contents.
.margin-example1 {
width: 200px;
background-color: #ddd;
/* shorthand for margin: 0 auto 0 auto, which is shorthand for specifying each side individually */
margin: 0 auto;
}
.margin-example2 {
width: 200px;
background-color: #aaccee;
margin: 0 auto;
/* we still need this to get the desired behavior */
text-align: center;
}
<div class="margin-example1">Example 1</div>
<div class="margin-example2">Example 2</div>
So how about a text input? Browsers usually style inputs as display:inline-block. This means we can center something inside them (Examples 1 & 2), but to center them within their container we need to change to display:block (Example 3) or because they are inline-like elements themselves, we can set text-align on the parent container (Example 4), see also.
.example1 {
width: 100%;
text-align: center;
}
.example2 {
width: 200px;
text-align: center;
}
.example3 {
display: block;
width: 200px;
text-align: center;
margin: 0 auto;
}
.example4 {
width: 200px;
text-align: center;
}
.example4-parent {
text-align: center;
}
<div>
<input type="text" value="Example 1" class="example1">
</div>
<div>
<input type="text" value="Example 2" class="example2">
</div>
<div>
<input type="text" value="Example 3" class="example3">
</div>
<div class="example4-parent">
<input type="text" value="Example 4" class="example4">
</div>
Layout in CSS can be complicated, but the basics aren't hard.
Note that I have over-simplified my explanation/definitions a bit (you can read all about the formatting model when you are ready).
Problem and source code
I'm trying to create <div>s within another <div> at the click of a button. When the button is clicked, a new inner <div> is created (within the outer <div>) with a unique id. I have this part working but here's where I'm running into an issue: I want each inner <div> to have a random margin-top.
Javascript
function pressButton() {
number += 1;
makeDiv(number);
};
function makeDiv(x) {
var innerDiv = document.createElement("innerDiv" + x);
outer.appendChild(innerDiv);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + ";display:inline-block;width:48px;height:48px;background-color:#000;");
};
CSS:
#outer {
position:absolute;
white-space:nowrap;
height:118px;
overflow:auto;
width:100%;
padding:2px;
}
Result (after button is clicked 4 times)
<div id="outer">
<innerDiv1 style="margin-top:15;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv1>
<innerDiv2 style="margin-top:23;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv2>
<innerDiv3 style="margin-top:37;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv3>
<innerDiv4 style="margin-top:0;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv4>
</div>
The result (which I got from inspecting the inner elements in my browser) looks like everything worked - all the margin-tops are random like I wanted. However, the visual result is this:
As you can see, the black inner <div>s all have the same margin-top. What am I doing wrong? How can I make the created <div>s all have random margin-tops?
The CSS spec requires that a length (other than zero) that is missing a unit be treated as an error (and thus ignored). Therefore, add px to the end of your generated margin number, and all should be well.
Live Demo
Description
This happens, because you set the display:inline-block; property. This makes them all to be in one line, so they will allign to the innerDivx that has the highest margin-top.
Delete the display:inline-block; property and give them float:left;. If you want to keep the gap between them, also add margin-left:5px;. And don't forget that margin-top's value needs a unit. I think you wanted to use px.
Also <innerDivx> is not a valid HTML tag. You should change them to a <div> and use innerDivx as an id attribute. Also your tags use almost the same CSS styles so you should put the same ones to a class and add the class instead.
Full solution code
HTML
<button id="button1">Add box</button>
<div id="outer"></div>
JavaScript
var number = 0;
document.getElementById("button1").addEventListener("click", pressButton, false);
function pressButton() {
++number;
makeDiv(number);
};
function makeDiv(x) {
var innerDiv = document.createElement("div");
outer.appendChild(innerDiv);
innerDiv.className += " box";
innerDiv.setAttribute("id", "innerDiv" + x);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + "px;");
};
CSS
#outer {
position: absolute;
white-space: nowrap;
height: 118px;
overflow: auto;
width: 100%;
padding: 2px;
}
.box {
float: left;
width: 48px;
height: 48px;
background-color: #000;
margin-left: 5px;
}
This is likely caused by the position model used for inline-block elements - they're all being vertically-aligned at their bottom line in a row.
I suggest that you simplify this and use position: block with float: left
http://jsfiddle.net/2y5bJ/4/
I also suggest that you stick to standard elements to ensure cross-browser compatibility - don't create your own elements called innerDiv1 etc, but use div elements with unique IDs.
function makeDiv(x) {
var innerDiv = document.createElement("div");
outer.appendChild(div);
innerDiv.setAttribute('id', 'innerDiv' + x);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + "px;");
};
I think there is no tag available with name
<innerDiv1>
This may be the cause.