I have been attempting to implement validation in JQuery, but it doesn't seem to be functioning correctly

Can someone assist me with adding validation in jQuery? I'm stuck and need help solving this problem.

$(function(){

        $("#btn").click(function(){
        var b=prompt("Enter your link");
        $("a").attr("href",b);      
        if($("b").val()=='')
        {
            var con=confirm("Please Enter your link");
            if(con==true)
            {
                var b=prompt("Enter your link");
                $("a").attr("href",b);

            }else
            {
                var pr=confirm("Please Enter your link");
            }

        }

    });

The provided html code is also shown below:

<html>
<head>
<script type="text/javascript" src="jquery-3.3.1.js"></script>
</head>
<body>
        <div id="div1">
                <a href="https://www.facebook.com"><h3>Facebook</h3></a>

                <img src="1.jpg" alt="My Images">

        </div>
<button id="btn">Attribute(a)</button>
</script>
</body>
</html>

I'm eagerly waiting for solutions, thank you.

Answer №1

<html>
  <head>
  </head>
  <body>
    <div id="div1">
      <a href="https://www.facebook.com"><h3>Facebook</h3></a>
      <img src="1.jpg" alt="My Images">
    </div>
    <button id="btn">Attribute(a)</button>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
  </body>
</html>

/////////////////////

$(function(){
  $('#btn').on('click',function(){
      var b=prompt("Enter your link");
      var link = $("a").attr("href",b);
    if(link.val()==''){
       var con=confirm("Please Enter your link");
       if(con==true){
           $("#btn").trigger('click');
       }
    }
  });
});

Answer №2

Let's take a look at this piece of code... if I comprehend correctly

you need to modify $("b").val()=='' because b is not an HTML element, but rather a parameter

Additionally, it would be more elegant to use onclick="func()" rather than

$('#btn').on('click',function(){...}
, however, the choice is yours

function func(){
        var b=prompt("Enter your link");
        $("a").attr("href",b);      
        if(b=="")
        {
            var con=confirm("Please Enter your link","");
            if(con!="")
            {
                var b=prompt("Enter your link");
                $("a").attr("href",b);

            }else
            {
                var pr=confirm("Please Enter your link");
            }

        }
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
  <a href="https://www.facebook.com"><h3>Facebook</h3></a>
  <img src="1.jpg" alt="My Images">

</div>
<button onclick="func()" id="btn">Attribute(a)</button>

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

The utilization of useEffect causes the page to go blank

Essentially, the issue is that once I include useEffect(() => { const fetchData = async () => { const result = await fetch('http://localhost.com/ping'); console.log(result) }; fetchData(); }, []); in my compone ...

Display HTML content using JavaScript only when a checkbox is selected

Currently, I am updating an HTML form to show additional subsets of questions based on the selection of a "parent" checkbox. The current implementation works well, but I am wondering if there is a more efficient way to achieve this without having to rewrit ...

Issue - Following error occurred in the file connection.js located in node_modules/mysql2 library: Module not found: Unable to locate 'tls' module

I've encountered an error in our Next JS applications where tls is not found. I have tried several troubleshooting steps including: 1. Updating Node modules 2. Using both mysql and mysql2 3. Running npm cache clean --force 4. Removing node_modules di ...

Looking for assistance with overriding kendo UI validation requirements

I'm looking to customize the date validation in my code to validate the date as DD/MM/YYYY. Here's my current code snippet and I'm getting an error message that says: Unable to get property 'methods' of undefined or null referen ...

Despite Nodejs's efforts, it was unable to successfully populate the user

I have been able to successfully reference and store other documents in my mongodb database as objectids for my application. However, I am facing an issue with the .populate method not working as expected. Below is the code snippet that I am using for po ...

Display/Hide Location Pins on the Map

Looking for some assistance, please. I'm currently working on a script to toggle the visibility of locations on a map. The main code I've been using can be found here, and my own code is displayed below: !DOCTYPE html PUBLIC "-//W3C//DTD XHTML ...

Issue with Internet Explorer: Refusing to run javascript included in AJAX-loaded content

While loading AJAX content that includes a javascript function using the jQuery .load function with done() on completion, I am facing an issue. $('#content').load(a, done); function done() { if(pagejs() == 'function') { ...

Seems like ngAfterViewInit isn't functioning properly, could it be an error on my end

After implementing my ngAfterViewInit function, I noticed that it is not behaving as expected. I have a hunch that something important may be missing in my code. ngOnInit() { this.dataService.getUsers().subscribe((users) => {this.users = users) ; ...

How can one display blog data (stored as a PDF) from a database alongside other different results (stored as

I have successfully displayed a PDF file from my database as a blob using the header("Content-type:application/pdf") method. Now, I am looking to also display some additional string results along with this PDF file. Is it feasible to achieve this while d ...

Transforming table data into a JSON format

My goal is to generate a specific JSON format from a table. The table consists of rows and 4 columns. You can view my table here. I aim to create a JSONArray based on the table. The first value in the left column serves as the key in the JSON, while the la ...

Issue with Typescript not recognizing default properties on components

Can someone help me troubleshoot the issue I'm encountering in this code snippet: export type PackageLanguage = "de" | "en"; export interface ICookieConsentProps { language?: PackageLanguage ; } function CookieConsent({ langua ...

Typescript allows you to apply a filter to an array

Query: Is there a way to display a pre-selected item from my dropdown using its unique ID? Issue/Explanation: The dropdown options in my web service are dynamically fetched based on a user's ZipCode. For example, a Provider is displayed as {Pho ...

Can you explain the distinction between 'rxjs/operators' and 'rxjs/internal/operators'?

When working on an Angular project, I often need to import functionalities like the Observable or switchMap operator. In such cases, there are two options available: import { switchMap } from 'rxjs/operators'; or import { switchMap } from ' ...

"CSS - Struggling with header alignment in a table display element - need help with positioning

During my HTML layout creation process, I encountered a peculiar positioning issue that proved difficult to resolve. Consider the following HTML structure: <div class="outer-wrap"> <div class="header"> I am a Header </div> <div c ...

What could be the reason for my code showing "success" instead of the intended outcome?

I'm currently working on a project that focuses on verifying whether ingredients are halal or haram. MongoDB is being used to store ingredient information, and express is managing the requests. After sending a GET request to /ingredients/{ingredientn ...

Updating a webpage using Ajax in Django

I've been diving into Django and am eager to implement ajax functionality. I've looked up some examples, but seem to be facing a problem. I want to display all posts by clicking on a link with the site's name. Here's my view: def archi ...

Problem with disabling dates on jQuery datepicker

After spending several days trying to solve this issue, I've decided to seek help. The problem at hand is disabling dates in my bootstrap datepicker using the following HTML code: <head> <!-- Required meta tags --> <meta charset="utf-8 ...

Ways to maintain a pointer to a RequireJS module?

Understanding the inner workings of RequireJS has been a bit challenging for me, as the official website doesn't provide clear explanations on fundamental concepts like how to utilize the 'require' and 'define' methods. Currently, ...

Steps to create a continuous blinking/flickering effect on a highchart pathfill

I am currently utilizing highcharts within one of my applications. I want to emphasize a particular stroke based on the content, and while I have achieved this already, I now need it to blink or flicker as if indicating an issue at that specific point. C ...

Dealing with the Spread operator in React and Redux causes issues

As a newcomer to the world of React and Redux, I find myself facing compilation errors while working on a reducer due to my attempt to utilize the spread operator. export default function chaptersReducer( state = { chapters: {}, isFetching: false, error ...