Passing HTML attribute to jQuery function from onclick event

I have a problem with passing one of the html elements to jQuery. I know that with attr() we can access attributes. However, I feel like I'm something wrong.

This is my simple jQuery function:

 <script type="text/javascript"> function test(value) { alert(value); } </script> 


I have a dynamic list created by a foreach loop:

 <select multiple="multiple" name="factors1" id="main_factors" style="width: 200px; height: 200px;"> <?php foreach ($array as $option): ?> <option onclick="test(<script>this.attr('title').value</script>);" id="<?php echo $option[0]; ?>" title="<?php echo $option[2]; ?>" value="<?php echo $option[0]; ?>"> <?php echo $option[1]; ?> </option> <?php endforeach ?> </select> 

I want when someone clicks on items in a list that shows their item in my inbox, for example. However, this code did not work for me.

 onclick="test(<script>this.attr('title').value</script>);" 

How can I send the value of the title attribute of my function from the onclick attribute?

Thanks in advance.

+4
source share
4 answers
 onclick="test(this)" function test(value) { alert($(value).attr('title')); } 

watch demo

+2
source

Try this code. I think you are wrong in your code.

 <select multiple="multiple" name="factors1" id="main_factors" style="width: 200px; height: 200px;" onchange="test(this.value);"> <?php foreach ($array as $option): ?> <option id="<?php echo $option[0]; ?>" title="<?php echo $option[2]; ?>" value="<?php echo $option[0]; ?>"><?php echo $option[1]; ?></option> <?php endforeach ?> </select> 

And in your jQuery:

 <script type="text/javascript"> function test(value) { alert(value); } </script> 
+2
source

You need to use the onchange event in the select element.

 โ€‹<select onchange="test(this.value)"> 

JavaScript:

 function test(value) { alert(value) }โ€‹ 

WATCH DEMO

0
source

Since you imported and use jQuery, it is better to separate the event handlers from your html elements, as a kind of separation of design from functionality:

Remove onclick completely from your php:

 <select multiple="multiple" name="factors1" id="main_factors" style="width: 200px; height: 200px;"> <?php foreach ($array as $option): ?> <option id="<?php echo $option[0]; ?>" title="<?php echo $option[2]; ?>" value="<?php echo $option[0]; ?>"><?php echo $option[1]; ?></option> <?php endforeach ?> </select> 

And bind the function to the change event from javascript:

 $(document).ready(function() { $('#main_factors').change( function() { test( $(this).val() ); // you can also do: // test( this.value ); }); }); function test(value) { alert(value); } 
0
source

Source: https://habr.com/ru/post/1432859/


All Articles