search by category with javascript - javascript

So I've been working on and off on a search function for awhile Tim Down helped me a lot and gave me a simple code to search the page for certain text.
Now I'm trying to edit the code to search by category. I've got the HTML table divided into divs as follows.
<form id="f1" name="f1" action="javascript:void(0)" onsubmit="searchpage()" >
<input id="t1" type="text" name="t1" />
<select name="category" id="category">
<option>all</option>
<option value="name">Title</option>
<option value="author">Author</option>
<option value="year">Year</option>
<option value="publisher">Publisher</option>
</select>
<input id="button" type="submit" value="SEARCH" name="b1" onclick="searchpage()" />
</form>
<tr>
<td>
<div id="name">
<div id="title">
title 1
</div>
extra content
</div>
</td>
<td>
<div id="author">
author 1
</div>
</td>
<td>
<div id="year">
2000
</div>
</td>
<td>
<div id="publisher">
publisher 1
</div>
</td>
<td>
<div id="notes">
notes 1
</div>
</td>
</tr>
<!--etc...-->
My Javascript is as follows
/*these two variables select the value attribute of each option in the dropbox*/
var cat=document.getElementById("category").selectedIndex;
var catid=document.getElementsByTagName("option")[cat].value;
function doSearch(text) {
var sel;
if (window.find && window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount > 0) {
sel.collapseToEnd();
}
window.find(text);
} else if (document.selection && document.body.createTextRange) {
sel = document.body.selection;
var textRange;
if (sel.type == "Text") {
textRange = sel.createRange();
textRange.collapse(false);
} else {
textRange = document.body.createTextRange();
textRange.collapse(true);
}
if (textRange.findText(text)) {
textRange.select();
}
}
}
function searchpage() {
doSearch(document.getElementById("t1").value);
}
As you can see, the value attributes match up with the ids in the divs. I'd like to make the javascript search only specific divs when the corresponding option is selected. Not sure how to go about it from here.
Can I use the "in" property to define that I want to search in a certain class or id?
something along the lines of
doSearch(document.getElementById("t1").value in document.getElementsByClassName("name"));}

The HTML pretty much stayed the same except I used classes instead of ids.
JAVASCRIPT
function doSearch(text) {
var catclass = document.getElementById("category").options;
var sel;
var classname;
var catselect;
if (window.find && window.getSelection) {
sel = window.getSelection();
window.find(text);
var classname = sel.anchorNode.parentElement.className;
var catselect = catclass[document.getElementById("category").selectedIndex].text;
while (classname !== catselect) {
if (sel.rangeCount > 0) {
if (sel.anchorNode.parentElement.className == catclass[document.getElementById("category").selectedIndex].text) {
break;
}
else {
doSearch(text);
}
}
}
}

Related

Activate textbox on change of an item in Drop down in HTML

I am trying to do the following:
I have drop down menu with four options in it. When I choose Shipped a text box should enabled. So I tried the following:
<div class="col-md-3">
<select class="form-control" id="ostatus" name= "ostatus">
<option value="Uploaded" <?php if ($dispatch_status == "Uploaded") echo "selected='selected'";?> >Uploaded</option>
<option value="Processing" <?php if ($dispatch_status == "Processing") echo "selected='selected'";?> >Processing</option>
<option value="Dispatched" <?php if ($dispatch_status == "Dispatched") echo "selected='selected'";?> >Dispatched</option>
<option value="Shipped" <?php if ($dispatch_status == "Shipped") echo "selected='selected'";?> >Shipped</option>
</select>
</div>
</div>
<input type="text" class="form-control" name="shipping_notes" disabled="true" id="shipping_notes" aria-describedby="" placeholder="Enter Shipping details">
Java script:
<head>
<script type="text/javascript">
document.getElementById('ostatus').addEventListener('change', function()
{
console.log(this.value);
if (this.value == 'Shipped') {
document.getElementById('shipping_notes').disabled = false;
} else {
document.getElementById('shipping_notes').disabled = true;
}
});
</script>
</head>
Doesn't seem to trigger? I don't see log on console too. What could be wrong here?
Update:
I have pasted the html code here:
https://justpaste.it/6zxwu
Update
Since you've now shared your other code I think I know what you want. You have multiple modals, each with a select list and shipping_notes textbox which should be enabled when the selection is Shipped for that particular modal. I've modified your HTML to get this working.
I've updated your HTML a bit. You have multiple elements with the same ID. HTML IDs should be unique. If you want to target multiple elements it's safer to use class (or data-) attributes. I've added class="order-status" to each select and class="shipping_notes_txt" to each textbox. I've used element.querySelector() and document.querySelectorAll() to select DOM elements.
The snippet below mimics two modals. When the select is updated, it only enables/disabled the textbox within the same form element.
// wait for the DOM to load
document.addEventListener('DOMContentLoaded', function() {
// get all select elements with class=order-status
var selects = document.querySelectorAll('.order-status');
// iterate over all select elements
for (var i = 0; i < selects.length; i++) {
// current element
var element = selects[i];
// add event listener to element
element.addEventListener('change', function()
{
console.log(this.value);
// get the form closest to this element
var form = this.closest('form');
// find the shipping notes textbox inside form and disable/enable
if (this.value == 'Shipped') {
form.querySelector('.shipping_notes_txt').disabled = false;
} else {
form.querySelector('.shipping_notes_txt').disabled = true;
}
});
// default value if status == Shipped: enable textbox
if (element.value == "Shipped")
{
var form = element.closest('form');
form.querySelector('.shipping_notes_txt').disabled = false;
}
}
});
.modal1 {
display:inline-block;
vertical-align:top;
padding: .5em;
padding-bottom:5em;
border: 1px solid black;
}
<div class="modal1">
<h3>First Modal</h3>
<div id="edit1" class="modal fade" role="dialog">
<form action="order.php" autocomplete="off" method="post">
<div class="col-md-2 ml-3 pt-1">
<label for="role" class="mr-3">Status</label>
</div>
<select class="form-control order-status" id="ostatus1" name= "ostatus">
<option value="Uploaded" selected='selected' >Uploaded</option>
<option value="Processing">Processing</option>
<option value="Dispatched">Dispatched</option>
<option value="Shipped">Shipped</option>
</select>
<input type="text" class="form-control shipping_notes_txt" name="shipping_notes" disabled="true" id="shipping_notes1" aria-describedby="emailHelp" placeholder="Enter Shipping details">
</form>
</div>
</div>
<div class="modal1">
<h3>Second Modal</h3>
<div id="edit20" class="modal fade" role="dialog" >
<form action="order.php" autocomplete="off" method="post">
<div class="col-md-2 ml-3 pt-1">
<label for="role" class="mr-3">Status</label>
</div>
<select class="form-control order-status" id="ostatus20" name= "ostatus">
<option value="Uploaded" >Uploaded</option>
<option value="Processing">Processing</option>
<option value="Dispatched">Dispatched</option>
<option value="Shipped" selected='selected' >Shipped</option>
</select>
<input type="text" class="form-control shipping_notes_txt" name="shipping_notes" disabled="true" id="shipping_notes20" aria-describedby="emailHelp" placeholder="Enter Shipping details">
</form>
</div>
</div>
Add onchange to your <select>
<select class="form-control" id="ostatus" name= "ostatus" onchange = "statuschange()">
And change the JavaScript to :
<script type="text/javascript">
function statuschange(){
var drpDownValue = document.getElementById('ostatus').value;
if (drpDownValue == 'Shipped')
{
document.getElementById('shipping_notes').disabled = false;
}
else
{
document.getElementById('shipping_notes').disabled = true;
}
}
</script>
assuming everything on the server side this works HTML comes first
<div class="col-md-3"> <select class="form-control" id="ostatus" name= "ostatus">
<option value="Uploaded" selected="selected" >Uploaded</option>
<option value="Processing" >Processing</option>
<option value="Dispatched" >Dispatched</option>
<option value="Shipped" >Shipped</option>
</select>
</div>
</div>
<input type="text" class="form-control" name="shipping_notes" disabled="true" id="shipping_notes" aria-describedby="" placeholder="Enter Shipping details">
document.getElementById('ostatus').addEventListener('change', function()
{
console.log(this.value);
if (this.value == 'Shipped') {
document.getElementById('shipping_notes').disabled = false;
} else {
document.getElementById('shipping_notes').disabled = true;
}
});

How to include Array Elements in Drop Down Box

I have an array in Javascript that consists of three different countries. I have a form in my HTML page that contains a drop down box. Instead of populating the drop down box using
<option value=""> *option name* </option>,
I want to try including the elements of my array in my drop down box, so when the user clicks it, they'll see the elements.
var countries=["Sri Lanka","Bangladesh","India"]
I tried using the 'onclick' function in my HTML so that it would link to this following function
function myFunction() {document.getElementById('Bangladesh').innerhtml= (countries[2])>
But I since removed it since it didn't work. How exactly can I populate the drop down box with elements from my array. My JS and HTML code have been provided below.
<DOCTYPE html>
<head>
<script src="inquiries.js"> </script>
</head>
<body>
<h1 align="center"class='header1'> <font size="8"> </font> </h1>
<div class="busybox">
<form name="myForm" form action="/action_page.php" onsubmit="return validateForm();" method="post">
<label for="fname"> <b> First Name </b> </label>
<input type="text" id="fname" name="firstname" placeholder="Your name......"
required >
<label for="Birthday"> <b> E-Mail </b> </label>
<input type="text" id="email" name="email" placeholder="Enter your E-mail address....." >
<Label for="country"> <b> Country </b> </Label>
<select id="country" name="country">
<option value="Sri Lanka"> Sri Lanka </option>
<option value="India"> India </option>
<option value="Bangladesh"> <p id="bangladesh"> </p> </option>
</select>
<label for="summary"> <b> Summary </b> </label>
<textarea id="summary" name="Summary" placeholder="Write a summary of your inquiry
here...." style="height:200px"> </textarea>
<input type="submit" value="submit" id="sbox" onclick="myfunction()">
</form>
----JS CODE----
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}else{
return true;
} }
var countries = ["Sri Lanka", "India", "Bangladesh"];
function myFunction() {document.getElementById('Bangladesh').innerhtml =(countries[2])>
var countries=["Sri Lanka","Bangladesh","India"];
document.getElementById("Select").innerHTML = "";
for(var i=0;i<countries.length;i++)
{
var node = document.createElement("option");
var textnode = document.createTextNode(countries[i]);
node.appendChild(textnode);
document.getElementById("Select").appendChild(node);
}
<select id="Select"></select>
Here is a solution using array#foreach.
var select = document.getElementById("selectCountry");
var countries = ["Sri Lanka", "India", "Bangladesh"];
countries.forEach((country) => {
var element = document.createElement("option");
element.textContent = country;
element.value = country;
select.appendChild(element);
});
<select id="selectCountry"></select>
Try this:
$('#country').change(function(){
var dropdown=document.createElement('select');
var options="";
for(i = 0; i < countries.length; i = i+1){
options+= "<option value='"+countries[i]+"'>"+countries[i]+"</option>";
}
dropdown.innerHTML= options;
document.getElementById('country').appendChild(dropdown);
});
To do it with jQuery:
$(document).ready(function() {
var select = $('#country');
var countries = ["Sri Lanka", "India", "Bangladesh"];
for (var i=0; i<countries.length; i++) {
var country = countries[i];
var el = $("<option value='" + country + "'>" + country + "</option>");
$(select).append(el);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<Label for="country"> <b> Country </b> </Label>
<select id="country" name="country">

JS- how to change option color base on if statment

I'm trying to change the option color base on an if statment. This is my form:
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
if (pro == 'Urgent') {
$("p").css('color', 'red');
}
if (pro == 'Critical') {
$("p").css('color', 'orange');
}
if (pro == 'Normal') {
$("p").css('color', 'green');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text" />
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="myFunction()">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
This if statement its what i want to do. but for now, any time im adding to the list another item with other option, all the colors are change to the last one.
you can see my problem here:
https://jsbin.com/selenifepa/edit?html,js,output
what should i do?
Use the :last-child css selector.
See this code
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
if(pro=='Urgent'){
$("p:last-child").css('color','red');
}
if(pro=='Critical'){
$("p:last-child").css('color','orange');
}
if(pro=='Normal'){
$("p:last-child").css('color','green');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text"/>
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="myFunction()">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
Instead of selecting all paragraph elements, you can select added element like this:
if(pro=='Urgent'){
$(lib).css('color','red');
}
if(pro=='Critical'){
$(lib).css('color','orange');
}
if(pro=='Normal'){
$(lib).css('color','green');
}
Replace your if with this one and this is it...
The issue is because the $('p') selector matches all existing p elements in the DOM, not just the one you added. You can fix that by using $(lib) to affect only the newly added p tag.
$(lib).css('color', 'green');
However, I would also suggest you look in to using unobtrusive event handlers as on* event attributes are considered outdated. As you're already using jQuery, here's how to do that:
$('#add').click(function(e) {
e.preventDefault();
var pro = $('#priority').val();
var $lia = $("<h5 />").text($('#task').val()).appendTo('#result');
var $lib = $("<p />").text(pro).appendTo('#priorit');
if (pro == 'Urgent') {
$lib.css('color', 'red');
}
if (pro == 'Critical') {
$lib.css('color', 'orange');
}
if (pro == 'Normal') {
$lib.css('color', 'green');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text" />
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button id="add">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
The reason is that you are selecting all the p tags with $('p'). Also, you have mixed jQuery with vanilla JS. I'll assume you want to use jQuery to simplify your code. Here it goes.
function add() {
// select the elements and assign to a var, that way we don't have to be selecting the elements over and over, which is 'slow' (research "Why traversing the DOM is slow")
var results = $('#results'),
task = $('#task'),
priority = $('#priority'),
// create the new div element with it's content
newResult = $('<div>'+task.val()+' '+priority.val()+'</div>');
// Decide what color to apply
if(priority.val() == 'Urgent'){
newResult.css('color','red');
}
if(priority.val() == 'Critical'){
newResult.css('color','orange');
}
if(priority.val() == 'Normal'){
newResult.css('color','green');
}
// append the new div to the list of results
results.append(newResult);
// clear the input and focus the cursor for the next value to be added
task.val('').focus();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text"/>
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="add()">Add</button>
<h3>List Result</h3>
<div id="results"></div>
Here This should do the trick
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
if(pro=='Urgent'){
lia.style.color='red';
lib.style.color='red';
}else{
lia.style.color='orange';
lib.style.color='orange';
}
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
document.getElementById('task').value = '';
}
The only issue was that you're selectin all the p elements by $("p"). You need to just select the currently added element i.e. lib. But lib is a javascript variable, so wrap it in jQuery to convert it into a jQuery object and then apply jQuery css.
e.g. $(lib).css('color', 'red');
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
if (pro == 'Urgent') {
$(lib).css('color', 'red');
}
if (pro == 'Critical') {
$(lib).css('color', 'orange');
}
if (pro == 'Normal') {
$(lib).css('color', 'green');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text" />
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="myFunction()">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>

JavaScript match selected text with div id

I am trying to show and hide certain div based on selected text in drop down list. The option in drop-down list is generated by getting id from certain class name. I thought of using looping of an array in javascript but am unsure how to do so. Sorry that i may sound unclear of what i wanted to do as i am lost and unsure how to do them.
My Codes:
JavaScript:
var elements = document.body.getElementsByClassName("headline-bar");
window.onload = function() {
var year = document.getElementById("year");
for (i=0;i<elements.length;i++)
{
var Entry = document.createElement("option");
Entry.text = elements[i].textContent;
year.add(Entry ,null);
}
}
Html:
<form>
<select id="year">
<option>All</option>
</select>
<input type="submit" value="Submit">
</form>
<form action="#" id="release_year" method="post" >
<div class="release_holder" id="2015" style="margin-bottom: 20px">
<div class="headline-bar">2015</div>
<div class="content">hello there</div>
</div>
<div class="release_holder" id="2014" style="margin-bottom: 20px">
<div class="headline-bar">2014</div>
<div class="content">hello there</div>
</div>
</form>
JavaScript Loop array that i thought of using:
var selectedText = yearSelect.options[yearSelect.selectedIndex].text;
var classList = document.getElementByClassName('press_release_holder').id.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
if (classList[i] === 'selectedText') {
//do something
}
}
Easier solution would to use querySelectorAll considering the condition of All option.
Use change listener for select-input.
var elements = document.body.getElementsByClassName("headline-bar");
var year = document.getElementById("year");
for (i = 0; i < elements.length; i++) {
var Entry = document.createElement("option");
Entry.text = elements[i].textContent;
year.add(Entry, null);
}
function showHide(elem) {
var val = elem.value;
if (val == 'All') {
[].forEach.call(document.querySelectorAll('.release_holder'), function(el) {
el.style.display = 'block';
});
} else {
[].forEach.call(document.querySelectorAll('.release_holder'), function(el) {
el.style.display = 'none';
});
document.querySelector('[id="' + val + '"]').style.display = '';
}
}
<form>
<select id="year" onchange='showHide(this)'>
<option>All</option>
</select>
<input type="submit" value="Submit">
</form>
<form action="#" id="release_year" method="post">
<div class="release_holder" id="2015" style="margin-bottom: 20px">
<div class="headline-bar">2015</div>
<div class="content">hello there</div>
</div>
<div class="release_holder" id="2014" style="margin-bottom: 20px">
<div class="headline-bar">2014</div>
<div class="content">hello there</div>
</div>
</form>
Fiddle Demo
You can use the onchange event in your drop down to fire your code:
<select onchange="myFunction()">
http://www.w3schools.com/jsref/event_onchange.asp
Then once myFunction() is fired, you get the selected text and set the CSS manually, as with this answer:
https://stackoverflow.com/a/21070237/5882767
use this on change function
<select onchange="myChangeFunction()">
function myChangeFunction(){
if( $('#year').val() == 'yourSelectedOption'){
$('.className').hide(); // use javascript function for hide show of element
}
}
Do the values of the dropdown list correspond to the year? i.e. the id of the div tag you want to hide.
If so, you can try the following:
var optionList = document.getElementById("year");
var selectedText = optionList.options[optionList .selectedIndex].value;
//hide the div with the id = selectedText
document.getElementById(selectedText).style.display = 'none';

Display fields when user selects particular value from combo box - Validation logic issue

I have a combo box, and there are 2 values to be selected from it. either Male or Female. When user selects Male then another 2 textboxes gets displayed. Those 2 text box cann't be empty (as they are being validated).
The problem : When the user selects Female, the 2 textboxes discussed above is hidden, and I am not allowed to navigate to the next screen without filling some values to those 2 fields (because its being validated). How can i solve this?
My COde
<table>
<tr>
<td align="left">
<select id="gender" name="gender" onchange='genderfind(this.value);'>
<option value="female">female</option>
<option value="male">Male</option>
</select>
</td>
<td id="gb" style="display:none;"> <td>
<input type="text" name="name" /></td>
<td align="left"><span id="msg_name"></span> </td>
<td>
<input type="text" name="lastname" /></td>
<td align="left"><span id="msg_lastname"></span> </td>
</td>
</tr>
</table>
</body>
JQUERY
function validateStep() {
var isValid = true;
var un = $('#name').val();
if (!un && un.length <= 0) {
isValid = false;
$('#msg_name').html('first name missing').show();
} else {
$('#msg_name').html('').hide();
}
// validate password
var l = $('#lastname').val();
if (!l && l.length <= 0) {
isValid = false;
$('#msg_lastname').html('last name missing').show();
} else {
$('#msg_lastname').html('').hide();
}
return isValid;
}
///
<script>
function genderfind(val) {
//alert(element);
if (val == 'male' ) {
document.getElementById('gb').style.display = 'block';
} else {
document.getElementById('gb').style.display = 'none';
}
}
</script>
After isValid = true; wrap the rest of the code just before return isValid; in an if loop if(document.getElementById('gb').style.display == "block") { /*[ your validation]*/
}
And your HTML code is incorrect. You cannot directly have a td inside another td. Its good practice if you put span or div or p or anyother element instead of the td's inside <td id="gb" style="display:none;">.
call validateStep() function only when the two fields are visible.
if($('#msg_name').is(":visible")){
validateStep ();
})

Categories