Angwenyi
Angwenyi

Reputation: 329

How do I get html tag value (div) in javascript

I have implemented this function (libphonenumber javascript )in a website http://www.phoneformat.com/

How do i get the value returned by this html tag. Whether Yes or No

< DIV id="phone_valid" class="popup-value"></DIV>' 

I have tried this

function checkSubmit(){
var country=$("#phone_valid").val();
if(country=="No")
{
    alert("Not a valid number");
    return false;
}

So far no luck

Upvotes: 2

Views: 35741

Answers (7)

Stphane
Stphane

Reputation: 3456

If you need to include HTML comments then consider using contents() method

$('#mydiv').contents()

Other wise html() method or even text() will be what you are looking for because val() purpose is for form elements ;)

Upvotes: 0

Tim S
Tim S

Reputation: 2329

.val() is for form elements. You should use .text() or .html() to get the value from a DIV.

HTML

<DIV id="phone_valid" class="popup-value"></DIV>

JavaScript

function checkSubmit(){
    var country=$("#phone_valid").html();
    if(country=="No")
    {
        alert("Not a valid number");
        return false;
    }
}

Hope this helps!

Upvotes: 1

RobotMan
RobotMan

Reputation: 488

you can use this:

document.getElementById("phone_valid").innerHTML;

Upvotes: 1

Andreas Louv
Andreas Louv

Reputation: 47099

In vanilla JavaScript you can use document.getElementById to get a specific node using ID:

var node = document.getElementById('phone_valid');

And then to get the text from that node you will need to use:

var text = node.innerText || node.textContent;

The jQuery .val() method is used on form fields like input, textarea, select...

Upvotes: 0

sacha barber
sacha barber

Reputation: 2333

You probably want to do this:

$("#phone_valid").html();

or

$("#phone_valid").text();

Upvotes: 1

Snake Eyes
Snake Eyes

Reputation: 16754

First, no space between < and div (saw here: < DIV id="phone_valid" class="popup-value"></DIV>' )

Second:

function checkSubmit(){
var country=$("#phone_valid").text(); // it is a div not input to get val().
if(country=="No")
{
    alert("Not a valid number");
    return false;
}

Upvotes: 1

Gurpreet Singh
Gurpreet Singh

Reputation: 21233

The .val() method is primarily used to get the values of form elements such as input, select and textarea.

Use

$("#phone_valid").text();

to get DIV text content or

$("#phone_valid").html();

if you want markup.

Upvotes: 3

Related Questions