Remember value across multiple buttons - javascript

I have an input box where you click it and it opens a reveal/modal/popup. These input boxes are dynamic/looped so I can't just pick the id.
foreach ($data as $row): ?>
<input type="text" id="Filler[<?=row["$i"]?>" name="PickedPlayer" data-open="exampleModal1" value="<?=$row["Player"]?>">
<?endforeach?>
Script
<script type="text/javascript">
function SendPlayer(str) {
$( "#Filler" ).val(str);
}
</script>
This returns the value of what I do in my modal to the first input on the page. If I start on the 2nd one it also returns it on the first. How can I have it store or remember the specific id across clicks, or just where the first click was.
EDIT: I do NOT want to select all of them. I want to select the second one. The one I clicked.

You can to use
document.getElementsByClassName("Filler")
to select all the elements with the class "Filler"
If you give the same ID to multiple elements it may not select all of them and is not reliable.

Try something like this
$("input").on ("click",function (){
var original=$(".original");
If (original.length===0){
$(this).addClass("original");
}
});
At that point it will only assign the unique class if it's never been assigned before so you only get the original input. You can then add and remove that class and other unique classes to keep track of your different inputs

Related

How can I add only unique options in multiple select tags which are in same class?

I need to dynamically add options to the select tags. Those options I will be fetching it from a file. There can be many selects in the form. Now I need to check all the selects whichever is in the same class If it doesn't have the option which I fetched from the file Then I need to add that option to that particular select.
var name = $(this).attr('name');
$('.slct').each(function(){
if($('this option[value="'+name+'"]').length==0)
{
$('<option>').val(name).text(name).appendTo(this);
}
});
When I tried the above code, Options are getting duplicated. For example I have 3 select tags. In the first tag I have an option called option1 remaining two tags are empty. Then after the execution of this code. First select tag contains the option1 twice and the remaining two tags contain only once. Can Someone tell me how do I do it ? I am new to jquery.
You can use find() to check if option with specific value exists in the select this way:
if($(this).find('option[value="'+name+'"]').length==0)
{
$('<option>').val(name).text(name).appendTo(this);
}
FIDDLE DEMO:
http://jsfiddle.net/3Lkv638x/1/

Why the JavaScript result always return first value?

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;

How to access attributes of dynamically created divs using jQuery

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");
});

Multiple checkbox scripts intervene with each other

a nice member here helped me set up a multiple checkbox example that stores the data to be shown in a div. However, when I try to do multiple of these, they interlap with each other and show the same data in the divs even when I changed variables.
I set up a simple example here:
http://jsfiddle.net/pufamuf/vrpMc/4/
Thank you for your time everyone :)
That's because you're using the same selector in both event handlers: input[type="checkbox"]:checked
This will select all checked checkbox inputs in the page.
You should instead use input[name="car[]"]:checked and input[name="phone[]"]:checked
to select only the inputs with the given name, each time.
In both your functions, you're selecting all of the selected checkboxes. My fix (and someone else might have a better one) would be to add unique ids to the ul's surrounding the li's.
html:
<ul id='electronics'>
<li><input type="checkbox" name="phone[]" value="Nokia" />Nokia</li>
That way you can modify your $('#submit').click handler to something like this:
$('#submit').click(
function()
{
var htmls = "";
$('ul#electronics>li>input[type="checkbox"]:checked').each(
function()
{
htmls += $(this).val() + " ";
}
);
$('.here').html(htmls);
}
);
Check out http://api.jquery.com/child-selector/, http://api.jquery.com/id-selector/ for more info.
Basically, without this or a similar change, there's nothing distinguishing your list of car brands from your list of electronics brands, and your click handlers both consider all of the checked checkboxes.

Removing an <option> from a <select> tag according to previously selected <option> tag? (POLL Example)for

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.

Categories