简体   繁体   中英

Passing variables to nested jQuery functions

I've got two input fields that each dynamically generate a small image with a red cross when they are filled with text. The idea is that the user can clear the text by clicking on that image. The javascript code is exactly the same with the only difference being the alt value of the image and the name attribute of the input box.

<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<script>
$( document ).ready(function() {

    $("input[type='text']").keyup(function(){
        var alt = "clear"+$(this).attr("name");
        if($(this).val() && !$("img[alt='"+alt+"']").length){
            $(this).after("<img src='images/cross.png' alt='"+alt+"'/>");
        }
    });

    $(document).on('click', 'img[alt="clearsource"]' , function(){
        $( "input[name='source']" ).val('');
        $(this).remove();
    });

    $(document).on('click', 'img[alt="clearlocation"]' , function(){
        $( "input[name='location']" ).val('');
        $(this).remove();
    });
});
</script>
</head>
<body>
    <form>
        <input type="text" name="source" placeholder="Source" /><br />
        <input type="text" name="location" placeholder="Location" />
    </form>
</body>
</html>

I wanted to make a reusable function through which I can pass two variables, and then call it twice. This is my attempt but it's not working. Can someone please help? Is it a scope issue?

Here is the JSFiddle version: https://jsfiddle.net/2bk86w4y/

<script>
$( document ).ready(function() {

    $("input[type='text']").keyup(function(){
        var alt = "clear"+$(this).attr("name");
        if($(this).val() && !$("img[alt='"+alt+"']").length){
            $(this).after("<img src='images/cross.png' alt='"+alt+"'/>");
        }
    });

    // == The function below replaces the duplicate functions in the previous code block. 
    // == Unfortunately it doesn't work. Please help :(

    function clearBox(inputname,imagealt){
        $(document).on("click", "img[alt='"+imagealt+"']" , function(){
            $( "input[name='"+inputname+"']"  ).val('');
            $(this).remove();
        });
    }

    clearBox("clearsource","source");
    clearBox("clearlocation","location");
});
</script>

Many thanks in advance!

You've got your parameters the wrong way round.

https://jsfiddle.net/daveSalomon/2bk86w4y/1/

clearBox("clearsource", "source");
clearBox("clearlocation", "location"); 

// should be...

clearBox("source", "clearsource");
clearBox("location", "clearlocation");

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