I'm trying to retrieve a list of users from a simple MySQL database table, e.g., called TableA, which looks something like: Username(varchar), Level(tinyint), DateCreated(datetime).
On an html page I have a search input box, say - and underneath it I have a div, say to display the results. I have it so that when I start typing a word (to look for a username), jQuery makes makes an ajax request to a php file which queries the TableA for the usernames.
The jQuery part looks like:
$("#search_bar").keyup(function()
{
var user = $(this).val();
$.post('get_user.php', user_name : user, function(data)
{
$("#result_box").html();
});
}
The php script, get_user.php, again is a simple script which looks something like
<?php
$user = $_POST['user_name'];
//connect db,
$query = mysqli_query (select Username from TableA where Username like '$user%');
//IMPORTANT PART HERE, I create a <DIV> or can be <P> and display it back
while ($row = mysqli_fetch_array($query))
{
echo "<div id="user_info" username='".$row['Username']."'>".$row['Username']."</div>
//I have the username as an attribute so I can make another .post request and get detailed user info.
}
?>
Now, previously using jQuery, every result that is being returned as a is being dumped in the result_box div ($("#result_box").html();). The problem I have with this is that if I have 3 users, say Mick, Mike and Mila and I start searching by typing 'M', the query returns all three (that's fine), however, when I click on a name, say the last one returned would be Mila, this will trigger another jQuery function which say for now just prints the name of the selected in a popup box - it however picks up the attribute of the first name, Mick, from the the first div that appeared there and not the one I clicked on. It's strange. If the search returns only a single entry then that's fine - however with multiple entries, regardless of which one I click, jQuery picks up only the first one.
I suspect its because the divs all have the same ID, and since they are being 'dynamically' created - jQuery just picks up the attribute (e.g., $("#user_info").attr('username') ) of the very first one or only one created?
Any help would be appreciated.
Thanks
You should use jQuery data()
You should create the div like :
<div class="userLink" data-username="$row['username']"></div>
And acces it from jQuery like
$('.userLink').on('click',function(e) {
var username = $(this).data('username');
}
And the attribute ID must be UNIQUE.
First off, you need to fix the issue of multiple DOM objects with the same id. Perhaps you can just use a class name. But, that probably won't fix your click issue. The click issue should be fixed by using the this reference that comes with the click event. This will tell you exactly which items was clicked on so even if there are multiple items, you can know which one was clicked on and can reference the attributes on that particular object with code like this:
$(this).attr("username");
FYI, you perhaps should use the HTML5 convention of data attributes. So, instead of an attribute of username="xxx", you would use data-username="xxx". Then, you can use:
$(this).data("username");
You can combine all these changes with delegated event handling to have a click handler like this:
Your PHP (switch to a class name and data-username attribute):
//IMPORTANT PART HERE, I create a <DIV> or can be <P> and display it back
while ($row = mysqli_fetch_array($query))
{
echo "<div class="userInfo" data-username='".$row['Username']."'>".$row['Username']."</div>
//I have the username as an attribute so I can make another .post request and get detailed user info.
}
Your delegated event handling click handler in the page:
$("#result_box").on("click", ".userInfo", function(e) {
var username = $(this).data("username");
});
Related
I have a drop-down menu in a form with elements retrieved from a database. Something like this :
for($i=0;$i<count($resq);$i++){
print("<li><a class=\"dropdown-item\" href=\"#\" id=\"$i\">{$resq[$i][0]}</a></li>");
}
$resq being an array containing the result of the query (i used mysqli_fetch_all).
As you can see I tried to dynamically generate the id of the items(first item has id=0, second has id=1 and so on till the final value of $i) but I think this is not correct.
Previously, I had the following JS code(which worked) which I used to set the drop-down value to the one selected by the user and to set the value of a hidden input to that value.(I know the code isn't elegant but I just wanted to test the logic in the first place)
var x=document.getElementById('dropdownMenuButton1slct');//dropdown
var c1=document.getElementById("0");//i - categories(IDs of the dropdown elements)
var c2=document.getElementById('1');
var c3=document.getElementById('2');
var c4=document.getElementById('3');
var c5=document.getElementById('4');
var p=document.getElementById('iaval');//hidden input from form
function clic(z){
z.onclick=function () {
x.innerHTML=z.innerHTML;
p.value=x.innerHTML;
};
}
clic(c1);
clic(c2);
clic(c3);
clic(c4);
clic(c5);
But now the same method won't work. If you can, please suggest me a different way or something, I am kinda stuck. I can provide more info if this seems vague or something like that. Thanks.
I'm using a combination of JQuery EasyUI and Select2 to be able to drag options from a right panel, onto a left select box.
In the original HTML, the select boxes are empty, and I only "add" anything to them if I drop an option on them,
<form id="section1">
<select class="select2" class="drop_target" id="selected_options" name="selected_options"></select>
<div>
<div class="draggable_option" data-id="1234">1234</div>
</div>
</form>
<form id="section2">
<select class="select2" class="drop_target"></select>
<div>
<div class="draggable_option" data-id="1235" id="selected_options" name="selected_options">1235</div>
</div>
</form>
Then in javascript, I do something like this,
$('.drop_target').droppable({
accept: '.draggable_option',
onDrop:function(e, source){
var $dragged_source = $(source);
var $drop_target = $(this);
}
});
The problem comes at this point, if you're dynamically adding things to the select, you have to check it doesn't exist, and if it doesn't, you create a new option, and add it,
var new_option = {
id: $drag_source.data('id'), data_id: $drag_source.data('id'),
text: $drag_source.val(), selected: true};
// Set the value, creating a new option if necessary
if (!$drop_target.find("option[value='" + new_option.id + "']").length) {
// Append it to the select
$drop_target.append(new Option(
new_option.text, new_option.id, true, true)).trigger('change');
}
var data = $drop_target.select2('data');
$drop_target.select2('data', data.concat([new_option]));
Clear as mud? Unfortunately it goes wrong at this point. While all calls to .select2 from $drop_target work as expected, this is not the select that was originally in the HTML, this is a div that select2 created, after hiding the original select, with an id attribute like id="s2id_selected_options". So when we append the new option to it, it doesn't get added to the select, and gets added to select2's div incorrectly instead.
My HTML pseudocode is deliberately set up in this "obtuse" way, because my page is like that. I have multiple forms, and multiple "identical" selects in those forms, generated by WTForms. So the "general" method of selecting your select by id, $('#selected_options') doesn't work correctly.
What I need to do, within the javascript, is gain access directly to the original, now hidden, select, and I can't access it via id.
When you have access to one of the elements that's "associated" with the generated by select2, you can access meta information for it via .data('select2'), or in this instance,
$(this).data('select2');
In here, there's loads of metadata that select2 uses (which you can see if you browse the source). For this question, to get the original select or input element, you can use,
var $drop_target = $(this).data('select2').opts.element;
Whether you're using a select, or an input, this gives you a jQuery element linking to it. If you're using a select, and are only interested in that, you can use the shorter option,
var $drop_target = $(this).data('select2').select;
This may be in the docs somewhere, but I was unable to find it, and I'm also not able to find it by searching now, because searching the docs for "data" and "select2" returns a result for nearly every page of their docs (hence the reason I'm answering this question myself, to hopefully save others the trouble).
So let us say i have a form with id #form which has two input fields, namely title & price.
I click on the Edit button somewhere in the application which has data attributes (e.g data-title="Apple" data-price="10")that are to be assigned to the #form upon clicking the button.
the obvious solution that works is
$("#name").val($(this).data('name'));
$("#price").val($(this).data('price'));
This obviously looks bad when you have too many fields. So I am trying to get something like this to work $('#form').data($(this).data());, more or less in a single like
Have tried this many ways with no success
Any help is appreciated
You could create a jquery plugin that you can call from the element that contains the data points and have it apply the data based on the key to elements within the form of that same name. Example below
$.fn.applyData = function(form) {
$form = $(form);
$.each($(this).data(), function(i, key) {
$form.find('#' + i).val(key);
});
};
JSFiddle: http://jsfiddle.net/LCM8S/43/
here is my problem. I'm currently trying to customize joomla article content with some module. As i'm trying out hide some div before the user had click on the input. Lets say user click Test1 which is a radio button , then another field which i hide with div will shown up the content of Test1. All the detail is load from mysql database.
Here is my javascript code that i trying to show the value. But it alway show me first value although i click other value suck as Test2 or Test3.
Example:
<script type="text/javascript">
function showBox1(){
document.getElementById('hideBox1').style.display ="";
var test = document.getElementById('123').value;
confirm (test);
</script>
Here is my php code:
<?php
// Get default database object
$db =JFactory::getDBO();
// Get a new JDatabaseQuery object
$query = $db->getQuery(true);
// Build the query
$query->select($db->quoteName('campusid'));
$query->from($db->quoteName('campus'));
$query->where($db->quoteName('collegeid').'='. $db->quote('1'));
// Set the query for the DB oject to execute
$db->setQuery($query);
// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if($results){
foreach($results as $result)
{
echo "<label class='option block spacer-t10'>";
echo "<input type='radio' name='$result->campusid' id='123' value='$result->campusid' onClick='return showBox1()'><span class='radio'></span>";
echo $result->campusid;
echo '</label>';
}
}
else{ echo 'Error';}
?>
As an example the output for first div is 3 radio button, each radio button had it own value. When user click on either 1 of the radio button then it should pass the correct value to be shown up so that i can bring the value to the next div to select my database data. Is there any mistake i had made on my code that make me alway getting the first value although i click other radio button?
Each radio button is an element in its own right. The radio group is not a single element.
Every radio button has the same id, which is invalid and not allowed in HTML.
When you getElementById, the browser attempts to perform error recovery and gets the first element with that id (ignoring the others).
If you want to deal with a group of elements, then:
make them members of a class
getElementsByClassName
Loop over the result and test the checked property
When you find a true checked take the value of that element
Your radiobuttons have the same id 123. You are selecting the element from the DOM using this id. Make sure every radiobutton has a unique id.
You don't even need the Id if you pass the element to the function.
HTML:
onClick='return showBox1(this)'
JavaScript
function showBox1(element){
confirm (element.value);
}
First of all, all the radio buttons have the same id attributes: "123".
The document.getElementById() function expects, that a certain id is only present once on a page.
If you want to get the selected value for the elements with id "123", then you should select like this:
var test = document.querySelector("#123:checked")[0].value;
If this doesn't work, then try:
var test = document.querySelector("[id=\"123\"]:checked")[0].value;
I have 50 rows of data and i want users to give them points by 1 to 50. I put dropdown boxes near them with options 1/50. But all i want is when a user selects 15(for example) for a row, 15 will be deleted from all other select tags of other rows. I am not as good as you in JavaScript. How can i accomplish this?
Hi casablanca i couldnt make he script you sent work. I need it to work on just one select tag so i give select tag an ID and an ID for the form too. I edit the scripts getElementsByTagName with getElementsByTagID (select tag's ID) to effect only one select tag. But the function doesnt triggered?
This might not be a very good idea, because it is very difficult for the user to modify choices -- for example, if I want to give 15 to a different option, I need to change the old one to something else and then change the new one to 15. Also, once all points have been assigned, it's impossible to make any changes because all options are gone.
A better idea would be to let the user do whatever he/she wants and then validate the form in the end. You could do that like this:
function validate() {
var used = []; // This array stores already used options
var rows = document.getElementById('myForm').getElementsByTagName('select');
for (var i = 0; i < rows.length; i++) {
var points = rows[i].value;
if (used[points]) {
// This value was already used
alert('Please choose a different value.');
rows[i].focus();
return false;
} else {
// This value was not used before; mark it as used now
used[points] = true;
}
}
return true;
}
And call this function in the onsubmit handler of your form:
<form id="myForm" onsubmit="return validate();">
EDIT1: id -> class
give each option the class of the number it is
<option class="15">15</option>
<option class="16">16</option>
etc.
Then jquery can remove() an item by class
$('.15').remove();
obviously have to do an on change and get the value just set. "remove()" is nice in this instance because I believe it will yank every instance of that class.
EDIT3: upon further consideration the above method would be further complicated by the need to not remove the "selected" option. Not going to figure out the exact method but I think changing the class from "15" to "selected15" with a $(this).append() or something of the sort before calling the remove would get the job done fairly safely.
EDIT2:
As noted by casblanca below this is not an ideal user interface at all for this type of input. You may want to look into this: http://www.utdallas.edu/~jrb048000/ListReorder/
Allows user to drag and drop items in a list to reorder them. Much more natural.