iam trying to hide all rows in table except for the ones with <td> containing same text as user selected from dropdown. thought it should be easy but im struggling with it for long now...i tried something like this:
$(document).ready(function() {
$('select[name=selectName]').change(function() {
$("td").each(function(index, paragraph) {
$td = $(paragraph);
if ($td.html() === $('select[name=selectName]').val()) {
//hide the matched row rather than remove it
$(not(this)).parent("tr:first").hide();
}
});
$('select[name="selectName"]').on('change', function() {
$("tr").show();
});
});
});
but it didnt work so i tried this:
$(document).ready(function(){
$('select[name=selectedName]').change(function() {
$('tr').filter(function () {
return $(this).find('td').filter(function () {
return $(this).text().indexOf('$('select[name=select2]').val()') == -1;
}).length;
}).$(this).parent("tr:first").hide();
});
});
but didnt work as well...this is how i build my dropdown:
$query = "SELECT user_name FROM users";
$result = mysql_query($query); ?>
<select name="selectedName" id="userSelected">
<option value="" disabled selected>user name</option>
<?php while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { ?>
<option value="<?php echo $line['user_name'];?>">
<?php echo $line['user_name'];?>
</option>
<?php } ?>
</select>
any help to lead for solution?? thanks
Knowing you have not posted enough info for us to help you finish, I can at least point out an error in your code.
You should use the F12 tools so you can spot these errors.
Depending on the browser you are using, the Console area of the F12 tools will show ReferenceError: not is not defined.
Clicking the line number will show that the error is
$(not(this)).parent("tr:first").hide();
(unless there's another error before this in which case you need to fix that first)
So not(this) is not valid syntax. If you don't understand why, please post a separate question, more specific, and we would be happy to explain the meaning of these things.
Are you looking to filter to rows containing the text in a given value, or rows whose entire html is equal to the text in the given value? This is an important difference, an I assume you mean the former since that's the wording you use, but your code seems to do the latter.
Also keep in mind that $(element).html() will give you a very different string from $(element).text(). In the following example, $('.bunny').text() will include the string "I am a bunny" but $('.bunny').html() won't.
<div class="bunny">
Hi! I am a <strong>bunny</strong>.
</div>
If you're looking to filter rows by their text contents, I'd do something like the following:
var search_term = $(this).val();
var matching_rows $('tr').filter(function(){
var this_row_text = $(this).text();
// Standardize whitespace (in case it's useful)
this_row_text = this_row_text.replace(/\s+/g, " ");
if (this_row_text.indexOf(search_term) > -1) {
return true;
} else {
return false;
}
});
matching_rows.addClass("highlighted"); // or whatever
Note that I created lots of variables at each step; even if the var is only used once, this can lead to much more descriptive and readable code that's less of a pain for you to troubleshoot and maintain later on. When my JS code is misbehaving, the first thing I do is I go in and break out variables like this. The resulting JS is about twice as many lines, but I almost always spot and fix multiple issues just by going through that process. Jquery makes it too easy to write overly dense code. ;-)
On a more general note, I think I spot a number of Jquery errors in your code snippets above. We could point those out individually for you, but that's not what SO is here for; focus on breaking your problem down into smaller and smaller pieces so you can tackle those errors one at a time, rather than being stumped by several of them acting up at once. For example, if you're trying to troubleshoot the filtering behavior, open up Chrome's dev tools and just start playing with filters in the JS console. Then once you're confident with that, you can copy & paste back into your IDE and be confident that "OK, I know these 3 lines are working as intended".
First set up some constants for the bits of the page that aren't going to change (this will help speed up your code):
var select = $('#userSelected');
var trs = $('tr');
Then in your change function you just need to test the text in each row against the value and toggle whether the the row is hidden or not:
$(document).ready(function(){
var select = $('#userSelected');
var trs = $('tr');
select.change( function() {
var value = select.val();
trs.each(function(){
var isShown = $( 'td:first', this ).text() == value;
$(this).toggle( isShown );
});
});
});
JSFIDDLE
Related
I wasn't sure how to search for the answer to this on here or on Google, so I figured I would just ask. I'm an affiliate for TicketNetwork and they have a plugin generator (you can see it here if you want: http://www.ticketnetwork.com/affiliates/plug-in-maker.aspx) where you can put in a keyword and it generates a list of events based on that keyword (basically like doing a search on their site). Here's an example of the code you'd put on your site:
<script type="text/javascript">
function TN_SetWidgetOptions() {
TN_Widget.newWindow = true;
TN_Widget.trackingParams = '';
TN_Widget.custLink = true;
TN_Widget.tixUrl = 'http://www.ticketnetwork.com/tix/';
TN_Widget.trackingLink = 'http://www.tkqlhce.com/click-12345-10793961?url=';
TN_Widget.CreateCustomUrl = function(row) {
return "http://www.tkqlhce.com/click-12345-10793961?url=" + escape(this.tixUrl + row[7] + "-tickets-"+ row[6] + ".aspx");
};
}
</script>
<script type="text/javascript" src="http://site_01504_011.ticketsoftware.net/widget3_c.aspx?kwds=austin%20city%20limits%20festival&style=9&mxrslts=10"></script>
My problem is, if a keyword returns no results, instead of giving some sort of "no results found", it just shows blank space. Is there some way I can manipulate this code to make it show something other than blank space if there are no results, or is that something TicketNetwork would have to add into their plugin generator?
I think you can do this in JQuery (Pseudocode)
if ($.trim($("#DIV").text()) === '') {
document.write('No Results Returned');
}
Just replace the DIV with the ID of the html tags surrounding your output. This is untested so you might have to fiddle with it a little bit but I think this is something that would work.
Also, don't forget you'll have to include the JQuery files to get this to work also.
EDIT: You can use $('#DIVID').text('No results Returned'); to point your code to wherever you want to display the text by JQuery selector.
First I just want to say thanks to the people who tidied up my question for me.
With the help of Bryant's answer I devised this solution:
<script type="text/javascript">
var nodelist = document.getElementsByTagName("TD").length;
if (nodelist == 0){
document.write("No tickets for this event are currently available.")
}
</script>
When there are no results, all it creates is an empty table with no cells. So, I just check if any table cells exist, and if there are none, it writes my message. I tried like a hundred different things before I landed on this, but I'm glad it works! :)
This has me stumped, and should be pretty simple.
I have an input in my html:
<input type="text" id="fafsaNbrFam" name="fafsaNbrFam" value="<%=nbrFam%>" class="hidden" />
System.out.println(nbrFam); // Works, gives me "6"
Then my js code:
$("#submit").click(function(e) {
var numEntries = 0;
var fafsaNbr = 0;
$("input[name^='name_']").each(function() {
if (this.value) {
numEntries++;
}
});
// EVERYTHING ABOVE HERE WORKS
fafsaNbr = $("input[name=fafsaNbrFam]").val();
alert(fafsaNbr + "X");
// WHERE THE 6 is I want to put the variable fafsaNbr, just hardcoded for now.
if (6 > numEntries && !confirm("The number of members you listed in your household is less than the number you indicated on your FAFSA. Please confirm or correct your household size. ")) {
e.preventDefault();
}
});
On my alert to test this, I get "undefinedX", so basically my jquery to get the value is coming up undefined.
EDIT: So it turns out my code wasn't the problem, but the placement of my input. Even though the original input placement was being processed, once I changed it, it all worked properly. Needless to say, I am still stumped.
You are missing the quotes around the name value. Try:
fafsaNbr = $("input[name='fafsaNbrFam']").val();
Your code is working fine,
I just added your code to jsFiddle and it works
Live EXAMPLE
Could you please make sure, the java scriplet is loading inside the value tag properly or not by checking the view source in browser?
Try to parse the value of the input like this:
fafsaNbr = parseInt($("input[name=fafsaNbrFam]").val());
Or Check whether the $("input[name=fafsaNbrFam]") is undefined or not.
I have two dropdowns. When selecting a value from the first (bron) I want to select an entry from the second.
This is fired from the onChange of the first dropdown.
function DepId() {
var bron = document.getElementById("IDUserDepartment");
var doel = document.getElementById("IDDepartment");
var bronwaarde = bron.options[bron.selectedIndex].value;
for ( var i = 0; i < doel.options.length; i++ ) {
var doelwaarde = doel.options[i].value;
if ( doelwaarde == bronwaarde ) {
doel.options[i].selected = true;
return;
}
}
}
But this does not work.
EDIT: for whatever reason, I never get a match. When I hardcode any of the values, and then do: doel.options[hardcodedvalue].selected=true, the option is selected. When I test for window.alert(doelwaarde) inside the loop, this always returns zero.
Any suggestions?
Your code should work, I see nothing wrong with it. If I may make three suggestions:
You might want to use jQuery: simpler code, better multi-browser support.
Use console.log instead of a window alert for debugging purposes: less intrusive, won't interrupt your testing (have a look at the developer console of your browser).
You might want to use English names for your variables, controls, etc. More developers will be able to read it, besides English is often shorter than Dutch ;)
I have a select box that is being populated dynamically from a database. As of right now the population of this check box is working flawlessly.
I have added functionality that consists of a button which on click calls isSelextBoxEmpty. The job of this function is to know whether this particular check box has been populated or not; if it has not then it will simply do nothing.
My problem is in determining whether this select box is empty or not.
Here is a very simplified example of what I am dealing with:
<li>
<label for="fruit_name">Fruit</label>
<select name="some_fruit" id="fruit_name" onclick="populate_box('fruit', this);">
</select>
</li>
My function, which is called from a separate button, looks like this:
function isSelextBoxEmpty(selectBoxId) {
var selected_value = $('#fruit_name');
/* More options... still testing the proper way:
var selected_value = $('#fruit_name').text;
var selected_value = $('#fruit_name').value;
var selected_value = $('#fruit_name').length;
var selected_value = $('#fruit_name option:selected', this);
var selected_value = document.getElementById('fruit_name');
var selected_value = document.getElementById('fruit_name').length;
var selected_value = document.getElementById('fruit_name').value;
var selected_value = document.getElementById('fruit_name').innerHTML;
*/
if (selected_value) {
alert("NOT null, value: " + selected_value);
// do something
}
}
Don't worry about what this does and how it does it. Right now what matters to me is that I can't check whether or not the checkbox is empty, I am just not sure how to go about it. I have read a lot through forums and documentation but there are many implications in doing this since it depends on the implementation itself.
For instance using document.getElementById(...)... will not necessarily return false and it depends on how you use it. Also using $("#someID")... in jQuery may or may not produce the desired results. I have already tried many different times as you can see in the commented lines, all of which can be evaluated in the if(...) statement.
How can this be done?
To check whether select box has any values:
if( $('#fruit_name').has('option').length > 0 ) {
To check whether selected value is empty:
if( !$('#fruit_name').val() ) {
One correct way to get selected value would be
var selected_value = $('#fruit_name').val()
And then you should do
if(selected_value) { ... }
Another correct way to get selected value would be using this selector:
$("option[value="0"]:selected")
Best for you!
Check this answer its tested and working well
if( !$('#id').val() ) {
// stuff here
}
I have a PHP form validation function that I developed in chrome and now will not work in firefox or Opera.
The function checks to see if a section of the form is blank and shows and error message. If there is no error then then the form submits through document.events.submit();
CODE:
function submit_events()
{
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && dj_amount.value==""){
//Error Control Method
//alert ('You didn\'t enetr an Amount for DJ\'s Card!');
var txt=document.getElementById("error")
txt.innerHTML="<p><font color=\"#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</font></p>";
window.document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
window.document.getElementById("company_amount_label").style.color = '#000000';
window.document.getElementById("own_amount_label").style.color = '#000000';
}else{
document.events.submit();
}
The document.events.submit();does work across all my browsers however the check statements do not.
If the box is not ticked the form submits. If the box is ticked it does not matter whether there is data in the dj_amount.value or not. The form will not submit and no error messages are displayed.
Thanks guys.
Here are some things I noticed. Not sure if it will solve the problem, but you need to fix some of these; some of them are just observations.
dj_amount is not declared nor referenced; my guess is you mean documents.events.dj_amount
You should put a ; at the end of every statement in javascript, including the end of var txt = document.getElementById("error")
You don't need to escape the string in the txt.innerHTML line; you only need to escape like quotes, such as "\"" or '\'', not "'" or '"'
You don't need the window.document referenced; document will do in almost all cases
EDIT - As Guffa points out, FONT is an old and deprecated element in HTML. It's not the cause of your problems, but modern markup methods mean you don't need it. Consider omitting and applying the style to the paragraph tag instead.
See edits below.
function submit_events() {
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && document.events.dj_amount.value == "") {
//Error Control Method
//alert ('You didn't enetr an Amount for DJ\'s Card!');
var txt = document.getElementById("error");
txt.innerHTML = "<p style=\"color: #FF0000;\"> You didn't enter an Amount for DJ's Card!</p>";
document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
} else {
document.events.submit();
}
}
Consider Firebug so that you can see and log to console javascript errors and messages:
http://getfirebug.com
I believe one of the above answers would solve your problem. For future reference, although it might not be suitable for your project, please know that writing forms and javascript feedback is much easier and faster when you use a library like jQuery.
To have minimal changes in code, just add this line before the first if statement:
var dj_amount = document.forms["events"].elements["dj_amount"];
However your code need serious optimization let us know if you're interested.
Edit: here is the optimization. First the "small" things - instead of whatever you have now for "error" container, have only this instead:
<p id="error"></p>
Now add this CSS to your page:
<style type="text/css">
#error { color: #ff0000; }
</style>
This will take care of the red color, instead of hard coding this in the JS code you now control the color (and everything else) from within simple CSS. This is the correct approach.
Second, right now you are submitting the form as response to onclick event of ordinary button. Better approach (at least in my humble opinion) is having submit button then overriding the form onsubmit event, cancelling it if something is not valid. So, first you have to change the function name to be more proper then have proper code in the function. Cutting to the chase, here is the function:
function ValidateForm(oForm) {
//declare local variables:
var oCardCheckBox = oForm.elements["dj_card"];
var oAmoutTextBox = oForm.elements["dj_amount"];
//checkbox cheched?
if (oCardCheckBox.checked) {
//store value in local variable:
var strAmount = oAmoutTextBox.value;
//make sure not empty:
if (strAmount.length == 0) {
ErrorAndFocus("You didn't enter amount for DJ's Card!", oAmoutTextBox);
return false;
}
//make sure it's numeric and positive and not too big:
var nAmount = parseInt(strAmount, 10);
if (isNaN(nAmount) || nAmount < 1 || nAmount > 1000000) {
ErrorAndFocus("DJ's Card amount is invalid!", oAmoutTextBox);
return false;
}
}
//getting here means everything is fine and valid, continue submitting.
return true;
}
As you see, when something is wrong you return false otherwise you return true indicating the form can be submitted. To attach this to the form, have such form tag:
<form ... onsubmit="return ValidateForm(this);">
And instead of the current button have ordinary submit button:
<input type="submit" value="Send" />
The code will be called automatically.
Third, as you can see the function is now using "helper" function to show the error and focus the "misbehaving" element - this makes things much more simple when you want to validate other elements and show various messages. The function is:
function ErrorAndFocus(sMessage, element) {
var oErrorPanel = document.getElementById("error");
oErrorPanel.innerHTML = sMessage;
document.getElementById("dj_card_label").style.color = '#FF0000';
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
}
Last but not least, the "new" code also makes sure the amount is positive number in addition to check its existence - little addition that will prevent server side crash.
Everything else is pretty much self explanatory in the function: naming conventions, using local variables.... most important is have as little redundancy as possible and keep the code readable.
Hope at least some of this make sense, feel free to ask for clarifications. :)
You should bring up the error console so that you see what the error actually is.
Lacking that information, I can still make a guess. Try some less ancient HTML code; the parser can be picky about code you add to the page using innerHTML:
txt.innerHTML="<p style=\"color:#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</p>";