Debug School

rakesh kumar
rakesh kumar

Posted on

how to apply condition if span element has no value using jquery and javascript

To apply a condition in jQuery to check if a element has no value, you can check its HTML content using the html()

<span id="mySpan"></span>
Enter fullscreen mode Exit fullscreen mode

// Check if the HTML content of the element with ID

if ($('#mySpan').html() === '') {
  // Do something if the <span> element has no value
  console.log('The <span> element has no value');
}
Enter fullscreen mode Exit fullscreen mode

In the example above, we use the $() function to select the element with ID "mySpan" and the html() method to get its HTML content. If the HTML content is empty, we execute some code to handle the condition. You can replace the ID parameter with any other valid selector based on your HTML structure.

Note that if the element contains only text and no nested HTML tags, you can use the text() method instead of html() to check its content. The text() method would return the text content of the element without any HTML tags.

To apply a condition using JavaScript to check if a span element has no value, you can use the textContent property of the element to check its value.

Here's an example of how to do this:

HTML:

<span id="mySpan"></span>
Enter fullscreen mode Exit fullscreen mode

javascript

const mySpan = document.getElementById("mySpan");


if (mySpan.textContent.trim() === "") {
  // Do something if the span has no value
  console.log("The span has no value");
} else {
  // Do something if the span has a value
  console.log(`The span has a value: ${mySpan.textContent}`);
}
Enter fullscreen mode Exit fullscreen mode

In this example, the if statement checks if the textContent of the mySpan element is an empty string. The trim() method is used to remove any whitespace characters before and after the text content. If the textContent is empty, the first block of code is executed, which logs a message to the console. Otherwise, the second block of code is executed, which logs the value of the span to the console.

jquery

 beforeSend: function() {

            if (!$('#showemailid').val()) {
                $('#emailiderror').html("Please  fill email");
            }
            if (!$('#Names').val()) {
                $('#nameerror').html("Please  fill name");
            }
            if (!$('#myuserpassword').val()) {
                $('#userpassworderror').html("Please  fill password");
            }

        },
Enter fullscreen mode Exit fullscreen mode

html

<div class="form-group"><input style="height:40px;" class="form-control" type="email"
                                        name="emailid" id="showemailid" placeholder="Email">
                                    <div class="col-12" style="color:red" id="emailiderror"></div>
                                </div>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)