简体   繁体   中英

how to get value from span through javascript?

<span class="modalclass" value="<? $product_name; ?>" onClick="alert(this.value)">hi
    <button type="button"  id="myBtnaa" value="<?= $product_id; ?>" onClick="alert(this.value)">BUY NOW</button>
</span>

When i click the span, not alerting the value($product_name) from span.It says undefined. In case of button it's working.

Your php script was not executed as you failed to use <??> or <?=?> :

value="<?=$product_id?>"

and

value="<?=$product_name?>"

Note that span don't have value attribute. Also its is not recommended to have inline onclick for nested elements. Try out HTML 5 data-* instead.

 .btn { border: 1px solid gray; line-height: 25px; background-color: ghostwhite; padding: 10px 5px; cursor: pointer; } 
 <span data-value="Hello" onclick="alert(this.getAttribute('data-value'))" class="btn">Click me</span> 

Note that span don't have value attribute, so I have replaced it to data-value

 <span class="modalclass" data-value="<?=$product_name?>" onClick="alert(this.getAttribute('data-value'))"> hi <button type="button" id="myBtnaa" value="<?=$product_id?>" onClick="alert(this.value)">BUY NOW</button> </span> 

You are passing product name through span and product id through button . Why ? JQuery / AJAX is a very strong tool for developers which ease out their lives , and you are making it complicated . If you want to display the product name and id on the page , display it in span , otherwise make it display: none . Check the code below :-

<script>
$(document).ready(function(){
    $("#myBtnaa").on('click', function(){
        var text = document.getElementById("myspan").innerHTML ;
        var res = text.split("|") ;
        alert(res[0]) ;
        alert(res[1]) ;
    });
});
</script>

HTML:-

<span class="modalclass" id="myspan" style="display:none;"><?php echo "8|Maggi Noodles" ; /*This value can come from two variables*/ ?></span>

<button type="button"  id="myBtnaa">BUY NOW</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM