Getting input event functionality with less default-styled elements - javascript

It's such an unnecessary detour to always style reset an input element when you only want the event functionality.
Is there any HTML element that offers events and as well allows me to styling-wise "start from scratch"?

DIV elements are not form elements.
There is no value or name attribute or property on a DIV element.
The easiest solution is to use an input element and remove all the default styling with CSS:
console.log(document.getElementById('div1').name); // undefined
console.log(document.getElementById('div1').value); // undefined
input {
border: none;
padding: none;
background-color: transparent;
outline: none;
}
<input type="text" value="Some text">
<div id="div1" name="name1" value="value1"> div content</div>

Related

Reset html required style with javascript

I have a form with an input with the attribute required set. When i submit the form and the input is empty, it shows a red border around it.
I am now looking for a javascript method to remove this, and reset the display of the input to the initial state.
After resetting and submitting again, the input should be checked again and show a red border if empty. Therefore i think setting css with :required does not give the desired solution.
A quick fiddle to illustrate my question:
jQuery(function() {
jQuery('#reset').click(function() {
//Clear red border of input
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<input id="myinput" required>
<input type="submit" value="submit">
</form>
<button id="reset">reset</button>
After clicking reset, the form should be shown as when the page is just loaded.
Edit
I tested this in firefox. In chrome the style automatically is removed when the element is onfocussed. However, i am still looking for a js solution to remove the message.
Edit, Updated
I want to reset the style, not prevent it from happening (when i dont
focus on it).
You can add a className to #myinput element which sets box-shadow to none and border to inherit at click on #reset element. Remove className at focus or change event on #myinput element, depedning on whether you want the box-shadow and border removed at focus on invalid input, or when user inputs a value.
.reset:-moz-ui-invalid:not(output) {
box-shadow: none;
border: 1px solid inherit;
}
When submitted, it shows a message like "This field is required". This
is removed when i unfocuss, but i am looking for a js method to remove
that message.
You can use invalid event, .setCustomValidity(" ") with a space character as parameter, called on event.target within handler.
You can use css :focus, :invalid to set border to red only when input gains focus and input is invalid. At html can add pattern attribute with RegExp \w+ to set input to invalid if value of input is empty string or only space characters
jQuery(document).ready(function() {
jQuery("#reset").click(function() {
jQuery("#myinput").addClass("reset")
});
jQuery("#myinput").focus(function() {
jQuery(this).removeClass("reset")
})
.on("invalid", function(e) {
e.target.setCustomValidity(" ");
})
})
#myinput:focus:invalid {
border: 1px solid red;
}
#myinput:focus {
outline: none;
}
.reset:-moz-ui-invalid:not(output) {
box-shadow: none;
border: 1px solid inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<input id="myinput" pattern="\w+" type="text" value="" required/>
<input type="submit" value="submit" />
</form>
<button id="reset">reset</button>
I cannot reproduce it here. But probably your problem is the pseudo-class applied to the input.
Given that you cannot remove pseudo-classes, maybe you can override the style. Something like:
:invalid {
box-shadow: none;
}
:-moz-submit-invalid {
box-shadow: none;
}
:-moz-ui-invalid {
box-shadow:none;
}
If you just need to apply the style when the reset button is clicked, add the styles to your own class and add/remove the class when needed.
The initial keyword makes a CSS property take the browser's default style, if this is what you're looking for...
jQuery(function() {
jQuery('#reset').click(function() {
//Clear red border of input
jQuery('#myinput').css('border-color', 'initial');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
#myinput {
border-color: red;
}
</style>
<form id="myform">
<input id="myinput" required>
<input type="submit" value="submit">
</form>
<button id="reset">reset</button>

Second append doesn't work on jquery

I have a form and need to append a field as many times as required. If the button CLICK TO ADD ANOTHER FIELD is clicked the div should be appended. After the first append (onload), the div responses correctly but from the second one on, I am not getting the similar response from the div. Here is my JSFiddle
If I click on the TEST BUTTON , I get alert for the first div but on adding another div (by clicking the CLICK TO ADD ANOTHER FIELD button) , the button (TEST) doesn't work anymore for the second div onwards.
I tried clone() to help this but unable solve this one. May be I am not using it correctly.
To replicate the issue please follow the steps::
Click on the CLICK TO ADD ANOTHER FIELD button to add div
Click on the TEST button on the second div onwards
Please take a look and suggest. Thanks in advance.
You have to use delegation like $(document).on('click','.test',function(){
var count = 1;
$.fn.addclients = function(add){
var mydiv = '';
mydiv = '<div class="dataadd"><fieldset><legend>Test: '+add+'</legend><b>Test Name :</b> <input type="text" id="ct'+add+'" name="cname" value="" style="width:250px" />'+
' <button class="test" id="test" style="float:left;">TEST</button>'+
'<br>'+
'</fieldset></div>';
//$(".dataadd").clone().appendTo('#registerForm');
$('#registerForm').append(mydiv);
}
$.fn.addclients(count);
$(document).on('click','#btn',function(){
++count;
$.fn.addclients(count);
return false;
});
$(document).on('click','.test',function(){
alert("test");
return false;
});
.zend_form{
font-weight:bold;
font-size:10px;
width:358px;
float: left;
}
.dataadd{
font-weight:bold;
font-size:10px;
width:358px;
//border: 1px solid;
margin-top: 15px;
margin-bottom: 15px;
//padding: 5px;
//float:left;
}
.selectbox{
margin-top: 15px;
width:155px;
height:100px;
}
.buttonc{
background-color: #fff;
width:145px;
height:45px;
}
.selection_area{
font-weight:bold;
font-size:10px;
}
input {
width: 200px;
}
dt {
width:50%; /* adjust the width; make sure the total of both is 100% */
}
dd {
width:80%; /* adjust the width; make sure the total of both is 100% */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="registerForm" enctype="application/x-www-form-urlencoded" method="post" action=""><dl class="zend_form">
<dt id="firstname-label"><label for="firstname" class="required">First Name:</label></dt>
<dd id="firstname-element">
<input type="text" name="firstname" id="firstname" value="" style="width:200px; float:left;" /></dd>
<dt id="middlename-label"><label for="middlename" class="optional">Last Name</label></dt>
<dd id="middlename-element">
<input type="text" name="middlename" id="middlename" value="" style="width:200px" /></dd>
</form>
<div style='display:table;background-color:#ccc;width:99%;padding:5px;'>
<button class='buttonc' name='btn_sub' id='btn' style='float:left;'>CLICK TO ADD ANOTHER FIELD</button>
</div>
You write:
$('#btn').click(function(){ ... });
but this will only bind the event handler to elements currently on the page when running this code. So elements added later will not be covered by this code.
But first tip: do not use a HTML ID (#btn) if you want to repeat it. So instead use a class (.btn), to capture all elements.
And then the best way is to write something like:
$(document).on('click', '.btn', function() { ... } )
This will capture any click event on the document (you could use a container div instead --just easier to show now), and only run the callback if it matches the given selector (.btn).
all elements created after body load must use delegation to work
$("body").on("click",".test",function(){
alert("test");
return false;
});
This way, the event is attached to the body, witch always exists, but only triggers when the matched elements appear, no matter when they're created (before or after js is loaded)

How to create a non-editable type(like tags) when a button is pressed

I got several buttons created in a loop dynamically.
<input class="btn btn-info attribute-button" name="commit" type="button" value="first_name">
And i got a text field.
<textarea class="text optional special form-control" data-role="tagsinput" id="campaign_message" maxlength="180" name="campaign[message]"></textarea>
these are created by my rails application.
and this is my js code to add the value of the button into the text field
$(document).on("click",".attribute-button", function(){
var value = $('.special').val($('.special').val() + $(this).val());})
what i want to do is this;
when a button is pressed i can already write the content on the text are but what i want is to write them as non-editable texts.User shouldn't be able to modify the added text.
http://timschlechter.github.io/bootstrap-tagsinput/examples/bootstrap-2.3.2.html
i found this lib but it didn't work out for me since it doesn't support a text are.He apply tags to all inputs.But i will have tags and input texts together.
how can i achieve this?
take a look at the awnser of this question. All you have to do is make the field readonly if you do not want people to add text.
Make textarea readonly with jquery
You can do this with a button click event
Here is my solution. There is a div with the class of tags. Inside it are divs with the class of tag and a text field with the class of newtag. When you enter text into newtag and hit space, enter or tab, a new tag div will be inserted. If you click a button with the class of attribute-button, its value will be added to a tag div. You will need to add thing to complete it such as a delete button on the tags to remove it.
Fiddle
HTML:
<input class="btn btn-info attribute-button" name="commit" type="button" value="first_name" />
<div class="tags">
<input type="text" name="newtag" class="newtag" placeholder="Add tags" />
</div>
JS:
$(".tags, .attribute-button").click(function(){
$(".newtag").focus();
})
$(".newtag").keydown(function(e){
if(e.which === 13 || e.which === 32 || e.which === 9){
e.preventDefault();
$(".newtag").before("<div class='tag'>"+$(".newtag").val()+"</div>");
$(".newtag").val("");
}
});
$(".attribute-button").click(function(){
$(".newtag").before("<div class='tag'>"+$(this).val()+"</div>");
})
CSS (optional):
.tags{
width: 400px;
height: 100px;
border: 1px solid #000;
margin: 5px;
}
.tag{
padding: 1px;
background-color: blue;
color: #fff;
border-radius: 3px;
display: inline-block;
}
.newtag{
border: none;
outline: none !important;
}

Checkbox image label Select effect only applying on hover, not when checked

I have check boxes which I have images set for the labels, and I'm using code which applies an effect when hovered over. However when tested in a fiddle the hover effect stays when selected and doesn't show the actual check tick box, only issue with the fiddle is that this only works on the last checked not all checked.
However when I apply this to my site only the hover effect works, the effect doesn't stay on any selected and the tick boxes stay visible.
The fiddle: http://jsfiddle.net/Zgh24/1169/
The only differences between that in my code is that the DIV it is in also has classes, I'm using bootstrap.
HTML:
<div id="sites" class="navbar navbar-inverse" style="padding:5px">
<input type="checkbox" name="site" id="so" value="stackoverflow" /><label for="so"><img src="http://sstatic.net/stackoverflow/img/favicon.ico" alt="Stack Overflow" /></label>
<input type="checkbox" name="site" id="sf" value="serverfault" /><label for="sf"><img src="http://sstatic.net/serverfault/img/favicon.ico" alt="Server Fault" /></label>
<input type="checkbox" name="site" id="su" value="superuser" /><label for="su"><img src="http://sstatic.net/superuser/img/favicon.ico" alt="Super User" /></label>
</div>
CSS:
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#sites label {
display: inline-block;
cursor: pointer;
}
#sites label:hover {
background-color: #ccc;
}
#sites label img {
padding: 3px;
}
JS:
<script>
$('#sites input:checkbox').addClass('input_hidden');
$('#sites label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
</script>
So my issue is sort of 2, I have a Fiddle which sort of does what I want, and then the fiddle I do have doesn't full work when I implement it.
I'm assuming I possibly have some css which is conflicting with that I'm trying to do, but I don't see how or what.
Any help is very appreciated -Tom
You could use only CSS pseudo class :checked and targeting next sibling label:
input[type=checkbox]:checked + label img
Finally, you should use as CSS rules:
#sites label:hover img,
#sites input[type=checkbox]:checked + label img {
background-color: #ccc;
}
DEMO jsFiddle
FYI, you could wish in some case to use instead of checkboxes radio buttons as in this jsFiddle:
http://jsfiddle.net/Zgh24/1173/
That could let you use persistant style on some element using only CSS with radio buttons hiddden:
http://jsfiddle.net/Zgh24/1174/
May be not sure.. the class .selected is used by bootstrap core and that style is applied to your label element.
Use your browser to see what style is applied.

How to change background-color of a "li" if I put the cursor in an input field inside the "li"? [duplicate]

This question already has answers here:
Is there a CSS parent selector?
(33 answers)
Closed 9 years ago.
Is it possible to set the background-color of the li when I put the cursor in a or b or c?
I have this list with 100 records and I want the hole row ("li") to show up in another color so it gets more easy to work with the list.
<li id=recordsArray_1>
<form medthod=post name=fr_1 id=fr_1>
<input type=text name=a> <input type=text name=b> <input type=text name=c>
<input type=submit name=b_1 value=ok>
</form>
</li>
<li id=recordsArray_2>
<form medthod=post name=fr_2 id=fr_2>
<input type=text name=a> <input type=text name=b> <input type=text name=c>
<input type=submit name=b_2 value=ok>
</form>
</li>
<li id=recordsArray_3>
<form medthod=post name=fr_3 id=fr_3>
<input type=text name=a> <input type=text name=b> <input type=text name=c>
<input type=submit name=b_3 value=ok>
</form>
</li>
.etc .... > 100
You can have a sibling element to the input elements and make it cover the li with background color on hover.
CSS
input[type=text]:focus~div {
background-color:red;
position: absolute;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
z-index: -1;
}
li {
position:relative;
}
jsfiddle
You can't do this with pure css, you'll need to use javascript / jQuery:
$("input[type='text']").focus(function(){
$("li").removeClass("background");
$(this).closest("li").addClass("background");
});
See: http://jsfiddle.net/HF5Tx/
Even though there is no parent selector, you have a hover state on the li triggered by the hover of the children (the hover bubbles).
One posibility is to use that state, and if you want to avoid the change when the cursor is on the li, but not on the inputs, just disable the hover event:
CSS
li {
position:relative;
z-index: 1;
pointer-events: none;
}
li:hover {
background-color: red;
}
input {
position: relative;
z-index: 2;
pointer-events: all;
}
fiddle
Is it possible to set the background-color of the "li" when I put the cursor in on of its children inputs?
No, unfortunately the :focus selector does not work on the ancestors of the focused element, so you cannot detect that. :active would, but does only flash in the moment of the click.
The :hover selector (applied to the li) could do it, assuming you're using mouse navigation it would have a similar effect - and also help while viewing the table, not only when filling out inputs. However, it doesn't work with keyboard-based navigation.
So you can only resort to JS (using jQuery for an example, same is easily achievable with native DOM):
var $lis = $("li");
$lis.find("input:text").focus(function(e) {
$lis.css("background-color", "none");
$(this).closest("li").css("background-color", "red");
});

Categories