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)
Related
I am a beginner in JavaScript. Currently I am learning about buttons, alerts and writing documents. For a fun little side project, I want to press a button and then it writes to a document. That works great, but I have other buttons to press but I do not know how to "go back" to the other page and push those other buttons. How can I maybe make a button to "go back" or user a timer? Which would be easier? Once I am on that other page, I don't want to stay there.
Example:
function myTest1() {
document.write("JavaScript")
}
<input type="button" onClick="myTest1()" value="What language is this?">
By keeping the buttons in a container and the displayed "page" in another:
function myTest1() {
// document.getElementBy('content') id to get the content element
// set innerHTML to change the content
document.getElementById('content').innerHTML = "JavaScript";
}
function goBack() {
// document.getElementBy('content') id to get the content element
// set innerHTML to change the content
document.getElementById('content').innerHTML = "Click a button to change this content";
}
<div id="button-container">
<input id="which-language-btn" type="button" onclick="myTest1()" value="What language is this?">
<input id="bo-back-btn" type="button" onclick="goBack()" value="Go back" />
</div>
<div id="content" style="border: 1px solid;">
Click a button to change this content
</div>
Or by changing both buttons and content:
function myTest1() {
// document.getElementBy('content') id to get the container element
// set innerHTML to change the content
document.getElementById('button-container').innerHTML = "JavaScript<input type=\"button\" onclick=\"goBack()\" value=\"Go back\" />";
}
function goBack() {
// document.getElementBy('button-container') id to get the container element
// set innerHTML to change the content
document.getElementById('button-container').innerHTML = "Click a button to change this content<input id=\"which-language-btn\" type=\"button\" onclick=\"myTest1()\" value=\"What language is this?\">";
}
<div id="button-container">
Click a button to change this content<input id="which-language-btn" type="button" onclick="myTest1()" value="What language is this?">
</div>
The idea is using innerHTML instead of document.write too avoid replacing all your document (including your script)
document.write clears the document when it's called:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
You could just keep appending the output to the body, but it's much better in the long run to adjust the content of a separate div, used for output, rather than just keep adjusting the body.
function myTest1() {
document.getElementById('output').textContent += "JavaScript\n"
}
#output {
width: 100%;
min-height: 20px;
background-color: rgb(20, 20, 30);
color: white;
margin-top: 20px;
font-family: "Lucida Console";
padding: 5px;
}
<input type="button" onClick="myTest1()" value="What language is this?">
<div id="output">
</div>
I´m not really sure I can do this, but it's worth the try.
I have a table with at least 10 items coming from a Mysql database. They are items for which you can bid. The idea is that every row (therefore, every item) has a button that can be clicked to enter the bid. This button opens a popup with a text field to enter the bid and a button to submit the form.
In order to identify the item the user is bidding for, I need its id, as well as the amount bid. The amount is really easy to get, but I´m struggling a lot with the item id.
Here is what I have:
$(document).ready(function(){
$(".show").click(function() {
$("#popup").show();
var $id = document.getElementsByClassName('show')[0].value;
console.log($id);
$("#jugador").val($id);
});
$("#close, #submit").click(function() {
$("#popup").hide();
});
});
#popup {
position: relative;
z-index: 100;
padding: 10px;
}
.content {
position: absolute;
z-index: 10;
background: #ccc;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: #000;
z-index: 5;
opacity: 0.4;
}
<td><button class="show" id="bid" value="<?php echo $row2["id"];?>"><img src="pictures/bidIcon.png" width="30" height="30"></button></td>
/*Popup*/
<div id="popup" style="display: none;">
<div class="overlay"></div>
<div class="content">
<header>
<div id="close">✖</div>
</header>
<form name="form1" method="post" action="bid.php">
<fieldset>
<label for="bid">Bid:</label>
<input type="text" name="bidAmount" id="bidAmount" size="8" />
<input type="hidden" name="item" id="item" />
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
<footer>
<button type="button" id="submit">Bid Now</button>
</footer>
</form>
</div>
</div>
I´ve been trying for a while with no luck. I will always get the item id for the first element no matter in which button I click.
Is it feasible what I want? Is this the correct approach? Should I use a different one?
Thanks a lot in advance.
Just change this line:
var $id = document.getElementsByClassName('show')[0].value;
To this:
var $id = $(this).val();
The problem is that with document.getElementsByClassName('show')[0].value you are querying the first occurrence of the .show button. With $(this) instead you will be accessing the current clicked button.
JQuery binds the events to the target where you attach the event, so this will always be a reference to the target of the event. Using $(this) will create a jQuery object of the target element permitting to apply jQuery functions to the element.
As a side note, you shouldn’t duplicate the elements ids. Every id must be unique in the html document, so it will be a good practice to make that id different for each button.
Hope it helps.
To access the current div element's Id you can use the ($this), which refers to the current javascript object.
$("div").click(function(){
alert($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1">Num 1</div>
<div id="2">Num 2</div>
<div id="3">Num 3</div>
<div id="4">Num 4</div>
Here in this example, i have created div's which when clicked return's the id of that div.
When you do it like this var $id = document.getElementsByClassName('show')[0].value; it will always take the first element having class="show".
Which will contain the first item hence always gives the id of first item.
So instead of doing it like that you can do it like this:
var $id = $(this).val();
This will select the current item on which user has clicked so will give the id of that item.
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>
I have been scratching my head since yesterday on this problem, which I cannot solve. I am a new starter to Twitter Bootstrap and everything was going well until yesterday.
I am using the latest JQuery v1.11.1 and Twitter Bootstrap v3.3.1. Yesterday I downloaded Bootstrap Tags Input, from here: http://timschlechter.github.io/bootstrap-tagsinput/examples/
The plugin works and I have changed the CSS styles to match my page layout but the problem I am having is that the placeholder attribute will not disappear when on focus. If I type in a tag and add a comma value the placeholder will show until I start typing and then it will disappear again.
I have tried using JQuery onfocus function to remove the attribute when onfocus but it doesn't do anything. What I want to achieve is that when onfocus the placeholder does not show at that point not even on blur.
My input field is demonstrated below:
<input type="text" name="customer_tags" id="customer_tags" value="" placeholder="Enter you tags" data-role="tagsinput" required />
two years later, but i found how to work around this issue. First, if you inspect the DOM , you will see a new input text, which inherits our placeholder text, but without the extra function onblur, onfocus that everybody mention before.
<div class="bootstrap-tagsinput">
<input placeholder="text inherited from our input" size="23" type="text">
</div>
Then, to fix this issue, you had to create a jquery function to point that input. Like this:
$('.bootstrap-tagsinput input').blur(function(){jQuery(this).attr('placeholder', '')})
pointing to element with the class "bootstrap-tagsinput" and then the "input" objects inside. You can add a .focus function too if you prefered. In my case, works when the user leave the object and the input tags look clean without placeholder.
HTML5 placeholder attribute will not disappear when you focus in the input tag... it will only disappear when you start typing. It is the default behavior.
You can see it # W3Schools as well...
Following code works in my case:
<input type="text" name="add_image_tags" id="add_image_tags" data-role="tagsinput"
class="form-control" placeholder="Enter tags" data-placeholder="Enter tags" value="" />
handlePlaceHolder(); //Call during page load
function handlePlaceHolder()
{
if($('#add_image_tags').val())
{
$('.bootstrap-tagsinput input').attr('placeholder', '');
}
else
{
$('.bootstrap-tagsinput input').attr('placeholder',$('#add_image_tags').attr('data-placeholder'));
}
}
$('#add_image_tags').on('itemRemoved', function(event) {
// event.item: contains the item
handlePlaceHolder();
});
$('#add_image_tags').on('itemAdded', function(event) {
// event.item: contains the item
handlePlaceHolder();
});
Try this, i hope it's working:
<form>
<div>
<label for="name" class="left-label">Your Name</label>
<input type="text" class="example-two" placeholder="Enter you tags" id="name" name="name">
</div>
</form>
CSS:
[placeholder]:focus::-webkit-input-placeholder {
transition: opacity 0.5s 0.5s ease;
opacity: 0;
}
.example-two:focus::-webkit-input-placeholder {
transition: text-indent 0.5s 0.5s ease;
text-indent: -100%;
opacity: 1;
}
body {
}
form {
display: inline-block;
margin-top: 20px;
}
label {
display: block;
text-align: left;
font: bold 0.8em Sans-Serif;
text-transform: uppercase;
}
.left-label {
float: left;
padding: 8px 5px 0 0;
}
input[type=text] {
padding: 5px;
text-indent: 0;
}
form div {
margin: 20px;
clear: both;
text-align: left;
}
JSFiddle
EDIT:
Working on IE too:
JSFiddle
That's how the plugin behaves. As soon as you hit "enter" or "comma" it creates a span tag (see image attached)and shift the input to the right. So now the input has no value and should show the placeholder.
In their docs it's mentioned [Search for confirmKeys]
Array of keycodes which will add a tag when typing in the input.
(default: [13, 188], which are ENTER and comma)
Change the confirmkeys to remove creation of tags when you type comma
Edit:
On your site I tried the below method in console and it worked.
$('input').tagsinput({
confirmKeys: [13]
});
I was able to do a quick fix using jquery. The behavior I wanted should do two things:
1) Remove placeholder while on page after I've focused and started typing. So I will run it on keyup.
$(document).on('keyup', '.bootstrap-tagsinput input', function(){
$(this).attr('placeholder', '')
})
2) If there are already labels in an input, then I don't obviously need a placeholder. I run this on page load.
$('.labels').each(function(){
var len = $(this).tagsinput('items');
if(len){
var $input = $($(this).prev().children('input').get(0));
$input.attr('placeholder', '');
}
})
In my case, after a little modification, it works fine.
$('#txtTimeSlot').on('change', function () {
var len = $(this).tagsinput('items').length;
if (len > 0) {
var $input = $($(this).prev().children('input').get(0));
$input.attr('placeholder', '');
} else {
var $input = $($(this).prev().children('input').get(0));
$input.attr('placeholder', $(this).attr('placeholder'));
}
});
for all who are still having this problem, just change the line in the javascript file:
from:
cancelConfirmKeysOnEmpty: true,
to
cancelConfirmKeysOnEmpty: false,
And thats all!
I wish there was a CSS selector that could do this, because I'm a complete noob when it comes to javascript.
The HTML is basically this:
<div class="searchmenu">
<form id="search">
<fieldset>
<input type="text" class="inputbox search"/>
</fieldset>
</form>
</div>
The CSS is this:
.searchmenu form {
display:none;
}
searchmenu:hover form {
display:block;
}
The form is already displayed when the div is hovered, now I also want it to keep it displayed while the input text is on focus.
I tried searching for other cases, but they either don't work for my case or I don't know how to implement them D:
DEMO
You can use jQuery focus & blur event.
Like this:
$('.inputbox').focus(function(){
$('.searchmenu').addClass('is_focused');
});
$('.inputbox').blur(function(){
$('.searchmenu').removeClass('is_focused');
});
CSS:
.searchmenu form {
display:none;
}
.searchmenu:hover form,
.searchmenu.is_focused form{
display:block;
}
.searchmenu{
background: #eee;
padding: 10px;
}
bind the input field to jquery event
For example
$(".inputbox .search").bind("focus keyup",function(){
$(".searchmenu").css("display","block");
});
I hope this would be helpful to you