0

In my project i have 10 products for every product i have button called info, if i click on a info button a form popups in that i wanted to fill the first field(product name) automatically ....lets say for product soap i have info button

                  `<a href="" id="1" class="btn">info</a>`

In the form

               `<form>
            <input type="text" id="product_name">
           <input type="text" id="number">
     </form>`

I want the field Product_name to be filled automatically based on button pressed so how to get this ..plz help i tried using <a href="" id="1" onClick="reply_click(this.id)">info</a> and my js

function  reply_click(clicked_id)
{
//alert(clicked_id);
 if(clicked_id == "1")
 {
  document.getElementById(product_name).value='Soap';   
 }
 else
 {
 alert("button not pressed");
 }

 }

i tried this logic for example, i am able to read button click but iam unable to write to form... some one please help me out Thank you in advance

2 Answers 2

3

You are using id without quotes product_name but 'product_name'

should be

 document.getElementById('product_name').value='Soap';   

instead of

  document.getElementById(product_name).value='Soap';   
Sign up to request clarification or add additional context in comments.

4 Comments

Just to add some clarification the way the OP has used it product_name would be a variable. If you intend it to be a string then it needs to be wrapped in quotes. Answer has been updated to clarify :P
@CarlMarkham that's the main problem, he is using id without quotes other wise OP's code is fine.
I know, I just thought I would add that for the OP incase it wasn't just a simple typo and they didn't understand.
hey thank you so much now it s working fine, actually i am new to javascript
2

As stated by Suman, you need to provide 'product_name' as a string to getElementById(). Here is a working example of your approach: http://jsfiddle.net/CTnFt/

But since you will likely have many of these tags for many products, a simpler solution might be to place the value in a data- attribute of your tag and read it in your javascript function, instead of a larger, harder to maintain collection of if/elses. Here is a working example: http://jsfiddle.net/Rc9MG/

<a href="#" id="1" class="btn" onclick="reply_click(this)" data-product-name="Soap">info</a>

<form>

    <input type="text" id="product_name" />

</form>

<script type="text/javascript">

    function reply_click(element)
    {
        document.getElementById('product_name').value = element.getAttribute('data-product-name');
    }    

</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.