Using jQuery to compare input with the current select optgroup choices

I'm struggling with looping through options within a form select. The options are grouped into optgroups, and I believe this is where my issue lies as I can't seem to find the correct syntax.

My objective is to compare the value entered using .val() with the text of the options in the list using .text(). If there is a match, I want to change the text color to red; if not, turn it green.

When I input an invalid id instead of sreportname here: $("#sreportname option"), the text always turns green. However, when I use sreportname, nothing happens. I'm stuck at this point.

Here is the structure of my form:

<form>
    <select name="sreportname" id="sreportname" class="form-control">
        <option value="zrxqy">--Choose a Report--</option>
        <option value="newReport">--Create a New Report--</option>
        <optgroup label="General Reports">
            <option>Abandoned Mines</option>
        </optgroup>
        <optgroup label="TPS Reports">
            <option>Farm</option>
            <option>Store</option>
            <option>Chicken Coops</option>
        </optgroup>
    </select>
    <input type="text" id="newReportName" name="newReportName">
</form>

And here is the jQuery code:

$(document).ready(function () {
    var exists = false;
    $("#newReportName").keyup(function () {
        $("#sreportname option").each(function () {
            if ($(this).text() == content) {
                exists = true;
                return false;
            }
        });
        if(exists) {
            $(this).css("color", "red");
        } else {
            $(this).css("color", "green");
        }
    });
});

I have put together a live example. Any suggestions would be greatly appreciated.

Answer №1

You're almost there! Just remember to extract the content variable from newReportName. Also, ensure that exists is nested within the keyup function:

$("#newReportName").keyup(function () {
  var exists = false;
  var content= $(this).val();
  $("#sreportname option").each(function () {
    if ($(this).text() == content) {
      exists = true;
      return false;
    }
  });
  if(exists) {
    $(this).css("color", "red");
  } else {
    $(this).css("color", "green");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <select name="sreportname" id="sreportname" class="form-control">
        <option value="zrxqy">--Choose a Report--</option>
        <option value="newReport">--Create a New Report--</option>
        <optgroup label="General Reports">
            <option>Abandoned Mines</option>
        </optgroup>
        <optgroup label="TPS Reports">
            <option>Farm</option>
            <option>Store</option>
            <option>Chicken Coops</option>
        </optgroup>
    </select>
    <input type="text" id="newReportName" name="newReportName">
</form>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to ensure that when displaying information boxes with Bootstrap, the inputs do not get misplaced or shuffled to the wrong location

I have been working on a form that needs to display an alert: https://i.sstatic.net/uGKtG.png When clicking the button next to the input control, an alert should appear. Although the alert is showing correctly, the input controls are shifting to the wron ...

What is the best way to incorporate an input bar in a Bootstrap panel header?

When designing a search box in my panel header, I floated both elements to get them onto the same line. Although functional, the vertical alignment of the title is displeasing and I am seeking a way to improve this without drastically changing its size. I ...

Implementing jQuery quicksand plugin using the .click event

Trying to incorporate a .click function into each image being sorted with the quicksand jQuery plugin. $('li img').click(function() { var verticalCenter = ($(window).height() - $('#popupContent').height() ) /2; var horizontalC ...

When a textarea contains a new line, it will automatically add an additional row and expand the size of the textarea

Developed a form with the functionality to move placeholders in a textarea upwards when clicked. The goal is to increment the height of the textarea by 1 row for every line break. However, I am uncertain about what to include in the if statement of my Ja ...

Adjusting the size of content with CSS

I've been attempting to get an image to cover the entire screen on a device using CSS, but so far I haven't had any success. The image is within an :after pseudo element and content tag. Since it needs to be laid over the HTML, I can't use t ...

Exploring the fundamentals of Jquery syntax and the powerful world of

I am facing an issue while trying to attach an onclick event during HTML generation. I am attempting to utilize the object ID for event binding using the foreach method. I am unsure about the syntax error that is causing trouble, and would appreciate some ...

Combining Custom JQuery with Nested JQuery UI Tabs

Currently, I am using the Slate Wordpress theme which includes shortcodes for tabs powered by jquery.tabs.min.js. However, I encountered a problem when trying to nest tabs using the theme's shortcodes. To solve this issue, I decided to create my own ...

Navigating URLs with Ajax Requests in CakePHP

How can ajax calls in javascript files located in the webroot be handled without PHP interpretation? In my project using CakePHP and require.js, I avoid placing javascript directly in views. To address this issue, I set a variable in the layout to store t ...

How can one save a text value element from a cascading list in ASP.NET MVC?

I have recently started learning about javascript, jquery, and ajax. In my model, I have defined the following classes: namespace hiophop.Models { public class CarMake { public class Category { public int CategoryID { g ...

Flow bar for micro-tasks

In my current project, I am faced with the task of organizing a series of 4 mini tasks and displaying to the end user which specific mini task they are currently on. To accomplish this, I have been utilizing image tags for each task. <img>1</img ...

Eliminating the loaded jQuery AJAX component

I was attempting to create a dialog using AJAX to load content, but I'm struggling to remove it once created. It was essential for the dialog to be multipurpose, PHP-compatible, draggable, and closable. (.center() function enabled) $('a.event& ...

By utilizing jQuery, I am orchestrating the movement of a series of div elements within a container with the simple click of a button

A group of div elements located within a container. When the button is clicked, the train should start moving. <script> $('document').ready(function(){ $("button").click(function(){ $("#train").animate({left: "300px"}, 2000); ...

Is there a way to ensure that all elements on a page display properly across all screen resolutions without being cut off?

My website consists of three main elements: pictures, Cards (containing pictures and various typography), and Buttons. These elements are arranged in a column layout. The issue I am facing is that the pictures and buttons get cut off on the screen due to ...

Creating an image slider that pauses on mouse hover

Here is a code snippet that I'd like to share <body> <div id="slideshow"> <div> <img src="assets/images/home-banner.jpg" width="995" height="421" alt=""/> </div> <div&g ...

Attempting to prevent the use of the <p> tag solely before the text

My toggle function is not working correctly in my FaQ section. When a user clicks on a topic, the bottom section should appear, but the <p> tag is being displayed across the entire line instead of just one word.. Here is an image to help illustrate ...

Tips for showing the chosen value of a ModelChoiceField in Django

Is there a way to display only the selected value from a forms.ModelChoiceField on a view page? I'm struggling to find a clear solution as a Python newbie, despite searching through various forums. Here is the form code snippet: class Manufacturer1F ...

jQuery: Implementing a function for all elements, including those dynamically loaded through Ajax later on

I have implemented a jQuery function to resize text areas, but I need it to work on all text areas. The function works well for existing text areas: $(document.ready(function(){$("text_area").resizer('250px')}); However, it fails to resize tex ...

Having difficulty locating the identification number of an item within the HTML coding

I'm currently trying to locate the ID of the "proceed to checkout" button for a bot that I am developing for my mother on the Best Buy website. However, it seems like the button's ID is hidden and I'm unable to determine how to uncover it. A ...

Tips on dividing a CSS file into separate lines for improved readability

I came across a dilemma while working with a 3rd party CSS file that is all one long line. Both the Sublime 2 text editor and Eclipse CSS editor were unable to split the file into easily readable style blocks. Can anyone recommend tools or methods for bre ...

Tips for maintaining color on <a> tags even after they have been clicked

My webpage has 3 <a> tag links to 3 different pages. I have set the hover state color to red, and now I want the background-color of the clicked page to remain as it was in the hover state. How can I achieve this? <html lang="en"> < ...