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.
Related
i have an input Element that Get Name of Helper but Two Element has same id
it is incorrect for Edit this problem,
i want to Add Parent Div Id to Child Input.how can i Append ParentId to ChildId
<div class="wrapper-merge-input">
<div id="Stb" class="col-md-6 ">
<label class="control-label">StartDate</label>
#page.Html.Raw(fromHtml)
</div>
<div id="Edb" class="col-md-6 ">
<label class="control-label">EndDate</label>
#page.Html.Raw(toHtml)
</div>
</div>
</div>
*And *
<input type="text" dir="ltr" class="form-control"
name="#name" id="#name"
value="#value"
onclick="DatePicker.Show(this,'#today');" />
for example #name+Edb
The code below shows how you can use .attr("id") to get an element's id. In order to travel up one level to the parent DOM element you should use .parent().
You can also use .attr("id", "new-id") to set an attribute value. This can take strings or variables (as in the code below).
By placing the update code into a function you can call it on page load, after a click or any other event. I have made it run after a click of the button so you can see the id change.
I added some basic styling to make the demo a bit nicer to use.
Let me know if you wanted something else.
WARNING you will likely want to make the updateID() function more specific, so it does not act on every input on the page.
// Click event for button to demonstrate change
$("#startUpdate").click(function() {
updateID();
});
function updateID() {
// Cycle through each input - WARNING - you will want to make this more selective
$("input").each(function() {
// Update id of input from it's own name and it's immediate parent's id
$(this).attr("id", $(this).attr("name") + "-" + $(this).parent().attr("id"));
// Print message to console to demonstrate id
console.log("new id = " + $(this).attr("id"));
});
}
.wrapper-merge-input {
border: 1px solid black;
border-radius: 5px;
padding: 8px;
margin: 20px;
}
#Edb {
padding-top: 10px;
}
#startUpdate {
margin-left: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper-merge-input">
<div id="Stb" class="col-md-6 ">
<label class="control-label">StartDate</label>
<input name="example1" id="example1" value="example1" onclick="DatePicker.Show(this,'#today');">
</div>
<div id="Edb" class="col-md-6 ">
<label class="control-label">EndDate</label>
<input name="example2" id="example2" value="example1" onclick="DatePicker.Show(this,'#today');">
</div>
</div>
<button id="startUpdate">Update IDs</button>
I am using JQuery for this:
Taking complete html and appending into a new div
My JQuery code:
$(document).ready(function(){
$("#addNew").click(function(){
var maindiv = document.getElementById('nestedFeilds').html();
$("#showhere").append('maindiv');
});
});
The HTML is pretty complex and lengthy so take just reference
<div class= "row" id="mainContainer">
<label for="Education" style="margin-left: 30px ; float:left;">Education</label>
<div class="col-xs-4 inner"></div>
<div class="col-xs-8 verticalLine" id="nestedFeilds" style=" margin-left: 10px ;float:left; display: none;">
In the last div, it is actually a form and I need its complete html to be shown with different name attribute when ever I click button
I am calling my function like this
<div id= "showhere"></div>
<div style="margin-left: 133px;float:left;">
<a id="addNew"> Add Education</a>
</div>
If you want to get innerHTML, you should use element.innerHTML, and if you want to append previously saved inner HTML, you can use element.append(variableWithPreviousInnerHTML). Here is the working example:
$(document).ready(function() {
$("#addNew").click(function() {
var maindiv = document.getElementById('nestedFeilds').innerHTML;
$("#showhere").append(maindiv);
});
});
div {
width: 100px;
height: 100px;
border: 1px gray solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nestedFeilds">Content from #nestedFeilds</div>
<div id="showhere"></div>
<button id="addNew">Click</button>
If anything isn't clear, feel free to ask.
Here is the sample code. I want to disable the click outside the search id. Just like we need in pop-up to disable outside click
<body>
You can search here
<div id="search">
Search
<input type="text" name=search><button>search</button>
</div>
</body>
You can create a div with fixed position that spans the entire screen and place what you want to be able to click inside of it, making all the clicks outside that element actually be on that "empty" div.
.disable-outside-clicks {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 10000;
}
.enabled-clicks {
width: 200px;
margin: 0 auto;
}
<div>
<button>This button will not work</button>
</div>
<div class="disable-outside-clicks">
<div class="enabled-clicks">
<button>This button will work</button>
</div>
</div>
You can use the :not() CSS selector combined with the .preventDefault() JS function :
$('*:not(#search)').click(function(e){
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I don't work !
<div id="search"></div>
maybe the css property pointer-events is the thing you are looking for.
add a class to the body element if the pop up is opened. let's say you will add the class .popup to the body element if the pop up is visible. then you can do it like this in css:
body.popup *:not(#search) {
pointer-events: none;
}
this means, that every element (*) in the body element with the class .popup, except the element #search is not clickable.
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)
you can view the following code on
jsfiddle too my full code is below
<html>
<head>
<title>Test Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<style>
.darkContent{
position: fixed;
background-color: white;
border: 5px solid black;
padding: 8px;
overflow: hidden;
color: #333;
font-family: arial;
}
.darkCover{
position: fixed;
left: 0px;
top: 0px;
z-index: 900;
background-color: black;
opacity: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
Show Box1
<form action="save.php" method="post">
<div id="useThisDiv1" width="500" height="500">
<h3 class="breadcrumb">Div TWO</h3>
<div class="row" id="popup3">
<div class="col-md-12">
<div class="portlet">
<div class="portlet-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<textarea rows="2" cols="50" name="notification_text"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 ">
<div class="portlet-body form">
<div class="form-body pull-right">
Cancel
save
<input type="submit" value="save" name="savethis">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<script>
$(function(){
function darkBox(div){
var w = (div.attr('width')) ? div.attr('width') : div.width();
var h = (div.attr('height')) ? div.attr('height') : div.height();
var box = $('<div></div>').addClass('darkCover');
$('body').prepend(box);
box.fadeTo('fast', 0.8);
$(this).keydown(function(e){
if(e.keyCode == 27){
box.hide();
contentBox.hide();
}
});
var contentBox = $('<div></div>').html(div.html());
contentBox.addClass('darkContent');
var x = $(window).width()/2;
var y = $(window).height()/2;
var endTop = y - h/2;
var endLeft = x - w/2;
contentBox.css("left", endLeft+"px");
contentBox.css("top", endTop+"px");
contentBox.css("z-index", "910");
contentBox.css("width", w+"px");
contentBox.css("height", h+"px");
$('body').prepend(contentBox);
contentBox.show();
}
$('.darkBox').each(function(){
var div = $($(this).attr('data-target'));
div.hide();
$(this).click(function(){
darkBox(div);
});
});
$('.add_case_note_cls').click(function(){
alert('foo');
console.log('foo');
});
});
</script>
</body>
</html>
If i click on any of them three buttons I don't get any response what so ever, I've two anchor tags and one submit button, they're not working. Their click events are not registering I tried both by calling them with their class names like $('.classname).click(function(){alert('foo);}); and by using calling them id's like $('#cancelbtn).click(function(){alert('foo);});.
once again jsfiddle link
I don't know what i'm doing wrong here, any Idea?
The main problem here is that you're essentially cloning your HTML when you show it. I'm not sure if that's what you're intending to do or not, but that's what you're doing when you do var contentBox = $('<div></div>').html(div.html());. So when you initially bind your click handler to the elements with the add_case_note_cls class, that only applies to the elements that currently exist in the DOM. However, the elements that you end up seeing, are created during the execution of your darkBox() function, and therefore do not have a click handler attached.
There are a few ways that you could go about rectifying this.
Move the binding of the click handler to be within the darkBox() function. Maybe right at the end of it.
Switch to using .on() instead of .click() for attaching click handlers. This will allow you to use delegated events, which will allow the click handler to fire on elements that are added to the DOM later. So instead of $('.add_case_note_cls').click(function(){ you'd have something like $('body').on('click', '.add_case_note_cls', function(){.
Use the original HTML instead of cloning it. This may or may not be an option depending on what your ultimate goal is here. If you're trying to use the same base HTML, but copy it to multiple places, then this won't work. But if you're not, then you should be able to do it.
Also, it's not the cause of your problem, but you have a typo here <a href="javascrip:;" id="saveNotification". You're missing a "t".
And if you want your click handler to fire on both of the links and the button, you need to make sure that you have the appropriate class on all of them.