I have a page which connects to a database where I have some users. Then, it takes each user and puts a div for each one of them, so I have 6 divs (a user in each div).
What I want is that, when somebody clicks in a div, it would give me the id of that user like if it was a form with an input.
I mean: the page takes the id and the name of each user from the database, so if I used a normal input, I would make that when the form is submitted, the form would return me the id of the selected user, but as I am using divs and no buttons, it would be nice to achieve that.
This is how my page looks (number 4 is where my mouse is):
The structure is basically, as I said, 6 divs, each one containing the name and the id of the user (I hide the names for privacy).
So, what can I do? If I haven't explained well I can give you more details... Thanks!!
Your HTML should be generated similar to this (each div has an attribute to point to its corresponding user from the DB)
<form id="select-user" action="formActionPage.php" method="POST">
<input id="selected-user" type="hidden" value="0">
</form>
<div id="1" class="user"></div>
<div id="2" class="user"></div>
<div id="3" class="user"></div>
The form has no submit button as you mentioned but has an input which is hidden notice that value=0 is a default value chosen by me .. you may control this in the action page ..
JQuery:
$("div").on('click', function() {
$('#selected-user').val($(this).attr('id'));
$('#select-user').submit();
});
EDIT
you may use div.[classname] div.user in my example, because you just don't want to apply this for any div
Use this:
HTML code:
<div><span id='userId'>10</span></div>
<div><span id='userId'>11</span></div>
jQuery code:
$("div").on('click', function() {
var userId = $("span", $(this)).text();
console.log(userId);
});
CSS code:
span {
display: none;
}
Main idea is to create in each div hidden span in which you will store user id, connected to this div. Also, you need onclick event, which will find this span and show needed id. Simple. Demo below.
DEMO
Note, that it is just an example. You can edit it as you need
Related
I want to set access permissions page where setting the permissions to the user to only view selected divs only for example:
There are 5 checkboxes in admin page and 5 divs in user page if check 3 div user has to get 3 div only I am mapping userlocation & client location & username for setting access permissions and how to display / hide the div in user page based on the checkbox selection or database values?
There is a user login separately and admin login separately. The admin will disable certain features for certain users. Using wcf rest and sql server as backend.
Before we get into the answer I have to mention security. You probably know, but for future readers benefit...you must not rely on simply hiding or not generating HTML elements as a means of restricting user access. Why - because when your form submits data to the server this can be observed with simple tools like Fiddlr. If you simply hide important inputs on the web page but still submit them, then a mischievous user could use something like Postman to edit and submit dodgy values to your server INCLUDING for the fields that were not visible on the form. Even if you have some server-side code to restrict the generation of the HTML for the restricted inputs, if a user is able to see a full form submit, or more likely if your API is self-describing or well documented, then they can fire up Postman and start sending your server all manner of hooky data.
For this reason it is vital that you re-validate the user, their role and their right to modify at the server at each interaction. Sermon over.
Assuming the above protection is in place then the way forward is relatively simple. In your HTML you assign classes to the elements that need to show/hide and you send a variable from the server to dictate their hidden or visible state.
For example, say you have two groups of users called usrNormal and usrAdmin. You might have an input defined as:
<input type="text" class="usrNormal usrAdmin" name="somedata" style="display:hidden;"></input>
<input type="text" class="usrAdmin" name="admindata" style="display:hidden;"></input>
<div class="usrNormal usrAdmin" style="display:hidden;">Some important info here....</div>
<div class="usrAdmin" style="display:hidden;">Some admin-only info here.... </div>
The key to this technique is the css class setting class="usrNormal usrAdmin"
And the accompanying JS function is:
var usrType = "usrNormal";
function protect() {
$("." + usrType).show();
}
protect();
I have used JQuery here in the line inside the function, you could use plain JS to achieve the same. We start the page with the important inputs, divs and other html elements hidden. The usrType setting comes from the server, and when the protect() function is called it finds all elements with the given user type class and makes them visible.
EDIT: See working snippet below. Though contrived the idea is clear I hope. One point to consider is the use of a generic marker class to indicate that the appropriate elements should take part in the show/hide operation. Let me know if you have any queries.
$( document ).ready(function() { // Important: wait for the document dom to be ready
// get the value of the server access variable - simulated by the radio buttons in this case
// var access = <you would put your server value here !>
var access = ".usrNormal";
setAccess(access);
// next part is just to let you play.
$('.serverVal').on('change', function(e){
setAccess($(this).val());
})
// key function - this will show pr hide based on classes.
function setAccess(accessVal) {
// next line finds all elements with class including 'usrAccess' and shows if they have the request class or otherwise hides.
$(".usrAccess").each( function() {
var ele = $(this); // readability
showHide(ele, accessVal);
})
}
// show or hide the element based on class
function showHide(ele, cls){
if ( ele.is(cls) ){ // pay attention - this uses the jquery 'is' feature.
ele.show();
}
else {
ele.hide();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form1">
<p>
<span>This selection simulates the value passed from the server. When changed the elements with the matching classes are shown or hidden.</span><br />
</p>
<p>
<span>
<input type="radio" class="serverVal" id="usrType1" name="usrType" value=".usrNormal" checked="1" />
<label for="usrType1"> Normal User only</label>
</span>
<span>
<input type="radio" class="serverVal" id="usrType2" name="usrType" value=".usrAdmin"/>
<label for="usrType2"> Admin User only </label>
</span>
<span>
<input type="radio" class="serverVal" id="usrType3" name="usrType" value=".usrAdmin, .usrNormal" name="usrType3"/>
<label for="usrType3"> Both </label><br />
</span>
</p>
<hr>
<p class="usrNormal usrAccess" style="display:none;">
<label for="somedata">Normal only</label>
<input type="text" name="somedata" />
</p>
<p class="usrAdmin usrAccess" style="display:none;">
<label for="admindata1">Admin only</label>
<input type="text" class="usrAdmin" name="admindata1" />
</p>
<p class="usrNormal usrAccess" style="display:none;">
<label for="someinfo">Info 1</label>
<textarea id="someinfo">This textare is visible to normal users...</textarea>
</p>
<p class="usrAdmin usrAccess" style="display:none;">
<label for="admininfo">Info 2</label>
<textarea id="admininfo">This textare is visible to only Admin users...</textarea>
</p>
</form>
So I am trying to store data to variables on the page when a button is clicked, there are multiple buttons and it needs to store data for that specific button. Each one of these buttons is nested inside a <form onsubmit></form> all the data I need to extra is within this form in different <input> and <div> tags. So using javascript or jquery how can I select the value of a specific and tag. So when the button is clicked on it adds this product to the cart, I want to take the productNumber, price, and quantity and store them to my own variables. When the button is clicked the forum calls onsubmit="ShoppingCartAddAJAX( this ); so I want to store this data in the ShoppingCartAddAJAX function.
Here is what one of the forms on the page looks like.
<form method="post" name="addtocart-501" onsubmit="ShoppingCartAddAJAX( this ); return false;">
<input type="hidden" name="formName" value="ShoppingCartAddAJAX" />
<input type="hidden" name="productNumber" value="758201" />
<input id="qtyproduct" type="hidden" class="hiddenqty" name="dmst_Qty_2805" value="1" />
<div class="price">
<div class="pricenew singleprice">
$7.99
</div>
</div>
</a>
</div>
</div>
</li>
</form>
So I have been trying to get this data by doing something like this.
var pn = $('input[name$="productNumber"]').val();
var qty = $('input[id$="qtyproduct"]').val();
In my javascript file the function looks something like this:
function ShoppingCartAddAJAX(formElement, productNumber) {
var pn = $('formElement.input[name$="productNumber"]').val();
var aa = $('formElement[name$="productNumber"]').val();
var qty = $('input[id$="qtyproduct"]').val();
}
But with alot more code... just showing that the function is passing in formElement and a productNumber.
But this is giving me the product number and quantity of the first product on the page, I need the data for which ever button the user decides to click on and there are multiple ones on the page not just one. I hope that when the button is clicked and that function is fired there is a way to look what forum it came from and then extract that data. I would also like to be able to get the price but it is stored in <div class="pricenew singleprice"> $7.99</div>.
Any help is greatly appreciated.
You are getting the product number and quantity of the first record since you have multiple input fields in the form with the name of productNumber(according to your description). So what basically happens here is when you call $('input[name="productNumber"]').val() jquery returns you the value of the first input field. Instead of that, do something like this inside your ShoppingCartAddAJAX function.
function ShoppingCartAddAJAX(form)
{
// Find child an element inside our form with the id of "qtyproduct"
// I used "find("#qtyproduct")" method so it searches anything nested inside your specific form element
// You can use "children("#qtyproduct")" method also
var qty = $(form).find("#qtyproduct").val();
var pn = $(form).find("input[name='productNumber']").val();
var pp = $(form).find(".pricenew.singleprice").text();
}
I have a html file that has a section for writing mdxquery , file sends queries to a js file and that file use this queries and other information and show a map on my html file, know i need to change this mdxqueries automatically by selecting different checkbox, i define different queries for different selections(my selectins are limmited), and now i want replace them in div section for it i defined different div(as you'll see dives are particular and the content of them is inside the div tag and arent changeable) that have different queries, now the problem is that, the js file read the queries ofdiv with just particular div, therefor i need to change the id of div , here is my cod that dont work, please see the code and tell me what is wrong:
<div class="first" style="width:80%;" id="mdxQueryEditor"
dojoType="GeoSOA.Spatialytics.widgets.MdxQueryEditor" title="MDX query editor"
submitButtonLabel="Submit"
mdxQuery="SELECT {[Measures].[report]} ON COLUMNS,
{[State].[City].members} ON
ROWS
FROM [ppgis]">
</div>
<div id="" class='second' dojoType='GeoSOA.Spatialytics.widgets.MdxQueryEditor' style='width:100%;display:none;'
mdxQuery='SELECT {[Measures].[report]} ON COLUMNS,
{[Boston].[City].members} ON ROWS
FROM [ppgis]'
submitButtonLabel='Submit'></div>
<div id="" class='third' dojoType='GeoSOA.Spatialytics.widgets.MdxQueryEditor'
style='width:80%;display:none;' mdxQuery='SELECT {[Measures].[report]} ON COLUMNS,
{([State].[All States].
[Boston].[Allston / Brighton], [Subject].[All Subjects])} ON ROWS
FROM [ppgis]'
submitButtonLabel='Submit'></div>
<script>
function generatorChoice(){
if(($("#Allston").is(":checked") )&&( !$("#All State").is(":checked")) && (!$("#Boston").is(":checked"))){
/*When the checkbox is checked*/
$(".first").attr("id", "");
$(".third").attr("id", "mdxQueryEditor");
$('.first').css('display','none');
$('.second').css('display','none');
$('.third').css('display','block') ;
}
}
</script>
I see a code $("#All State").is(":checked"), this could be potentially wrong.
Here you are trying to grab element with Id - "All State", but HTML Id's cannot have spaces in between, If that's not meet code inside If condition will not be executed and Id will not change.
I usually use getElementBy, for example I do this
var myDiv = document.getElementById('div1');
myDoiv.setAttribute('id', 'div2');
I am doing a portlet in Liferay with a form like this:
<form method="post" action="<%=actionAddRule.toString() %>" id="myForm" >
<aui:select name="attribute" style="float: left;">
<c:forEach var="attr" items="${fields}">
<aui:option value="${attr}" selected="${condition.attribute==attr}">${attr}</aui:option>
</c:forEach>
</aui:select>
<aui:input type='button' value="Add Condition" name='addCondition' onClick="addCondition();" %>'></aui:input>
<div id='conditions'></div>
</form>
I want that when someone click the button add a new select, but I don't know how do a new . I tried do it with JavaScript with:
var conditions = document.getElementById('conditions');
conditions.innerHTML('<aui:select ...>...</aui:select>');
and
document.createElement('<aui:select>');
I tried too with AUI script doing:
var nodeObject = A.one('#divAtr');
nodeObject.html('<aui:input type="text" name="segment21" label="Segment" value="lalal" />');
But it doesn't work because is html and doesn't can make AUI, and if I make the new select with HTML normal, when I catch the values some are lost.
Thanks.
As #Baxtheman stated, this won't work because the tag is not a client-side HTML tag, but a server-side tag from the aui-taglib.
To dynamically load the contents of the select box you would want to follow these steps:
add an element in your JSP, but make it hidden
<aui:select id="conditions" style="display: none;"><aui:select>
From your javascript, when the event occurs that you want to use to load your second select box, you would select the dropdown box and add the options you wish to it with something like the answer from this post Adding options to select with javascript
Make sure you set the select box to be visible after loading the options.
document.getElementById('<portlet:namespace/>conditions').style.display = 'block';
For more clarity, the reason you're missing information on POST if you add a normal HTML select box, is because of the way the aui:form serializes the data. I believe the ends up with a custom onSubmit that gathers only the aui elements.
<aui:select> is a JSP taglib, not the final HTML markup.
If you understand this, you resolve.
I am not a JavaScript person really, I write in ASP and use a SQL database in the backend. But our marketing director requested a change that will use JavaScript.
On our view cart page, we're currently displaying an input box with a modify button to allow customers to change the quantity of the listed item (in that row... there could be multiple products in their cart, each having their own quantity input).
<form method="post" action="updateitem.asp">
<input type="hidden" name="product_id" value="<%= PRODUCT_ID %>">
Quantity: <input type"text" name="quantity">
<input type="image" name="Submit" src="/graphics/modify.gif" align="middle" border="0" alt="Continue">
</form>
What I'd like to make work is something like this. Hrm, assuming I need to do my form/div name differently for each product? I can easily write the product_id into the id tags but then assuming I'd also need to loop through my function for each one. I've gotten this far in writing the replacement code:
Get Dataset from Database (items in cart) and loop through:
<form method="post" action="updateitem.asp" id="updateitems<%= PRODUCT_ID %>">
Quantity: <input type="text" name="qty<%= PRODUCT_ID %>" OnChange="Javascript:UpdateQty()")
<div id="showlink<%= PRODUCT_ID %>">
<br /><span class="BodyTiny">update</span>
</div>
</form>
END LOOP
So if the quantity changes, it displays the word "update" where they can click and it passes whatever quantity that is in the quantity field to the updateitem.asp (in a way I can then update it in the database in ASP/SQL). In the code above, if we could just insert the new # in the a href statement after quantity=, then I could fix it in the updateitems.asp page without a problem.
I'm not sure where to even begin honestly, I have this so far:
LOOP through dataset so each product has its own function
<script Language="JavaScript">
<!--
function UpdateQty(updateitems<%= PRODUCT_ID %>) {
Show div updateitems<%= PRODUCT_ID %>
Replace NEWQUANT within that div with the value in the input field qty<%= PRODUCT_ID %>
}
//-->
</script>
END LOOP
I'm having a few problems...
I am not sure how to write the function UpdateQty. It should A) display the stuff in div id=showlink, and B) add the # from the input named quantity quantity to the href so I can update it in the database on the next page
If they have JavaScript turned off, they should be able to enter a new quantity and just hit enter for it to submit the form. I believe this will work as its a form with 1 text input and 1 hidden one, so just hitting enter in the text input should submit it. But that should still work with whatever JavaScript is added to make the showlink div show if it changes.
Do I need to add a class to my CSS for showlink? If so, what do I need to put in it?
Any help would be greatly appreciated!
Mahalo!
so what you can do for updateQty is have one function that will be correct for all products in a list just by making a function that finds all the necessary elements by relative paths.
//in this function the context is the element, so the
//`this` variable can be used rather than a param
//for the product id
function updateQty() {
//show the update link
var parent = this.parentNode;
//assumes only the update text uses the class bodyTiny, and that there
//is only one element using it. obviously making this invariant true
//would be trivial by adding a different class name
var updateText = parent.getElementsByClassName("bodyTiny")[0];
updateText.style.display = 'block';
var updateLink = updateText.parentNode
, updateHref = updateLink.href;
//next we find the current quantity and replace it with the input
updateHref = updateHref.replace(/qty=(\d*)/, 'qty='+this.value);
//then we set the link element's attribute
updateLink.href = updateHref;
//now when you mouse over the link you should see the url has changed
}
You can also set your form to POST the equivalent data, and then I guess on the server side you will have your OnGetPage and OnPostback both delegate to the same method with the parameters either parsed out of the query string or out of the post data.
You can see it running on jsfiddle. Hopefully this helps!