0


I have very recently started to learn Javascript to help me at work and I can't help but think I've bitten off much more than I can chew.

The idea:
Using a form, take a single piece of inputted information, prefix and suffix the information with a predefined values and output it to a textarea so that I can copy/use it.

For some reason, I've found learning javascript particularly hard so far, and the code I've put together does work, exactly how I want but I can't help but think the code I've thrown together is incredibly sloppy.

The Form

<form name="invalidateForm"  action="">
Image Name:<br /><input id="imageName" type="text" name="imageName" value=""><br />
<input class="btn" type="button" onclick="invalidateUrls()" value="Generate URLs">
<input class="btn" type="reset"><br />           
<textarea id="icdnResults"></textarea>
</form>

The JavaScript

<script type="text/javascript">
function invalidateUrls()
{
var txt = "";
document.getElementById("icdnResults").value = "";

if (document.getElementById("imageName").value != ""){
txt = "";

//Category Thumbnails
txt += "prefix text";
txt += document.getElementById("imageName").value;
txt += "suffix text\n";

//Product Page Main Image
txt += "prefix text 2";
txt += document.getElementById("imageName").value;
txt += "suffix text 2\n";

//Flyout image on product page
txt += "prefix text 3";
txt += document.getElementById("imageName").value;
txt += "suffix text 3\n";

//Product page thumbnails
txt += "prefix text 4";
txt += document.getElementById("imageName").value;
txt += "suffix text 4\n";

document.getElementById("icdnResults").value += txt;
}
}
</script>

I'm 99% sure that what I've done takes it one step further than sloppy and I'm also guessing that it's not 'future proof' in the slightest.

Should I be using and defining variables more, or is there a completely different way of doing it?

If someone could tell if I'm on the right tracks or if I should completely scrap it, it would be greatly appreciated.

Thanks :) Alex

EDIT
My apologies to anyone that read this, it would seem I didn't properly explain and forgot to mention one critical thing; the prefix and suffix both have 4 different strings. So, the user would input a value into the input field and it would prefix this with 4 different values, and also suffix with 4 different values.

http://www.somedomain.com/folder/?fmy=<<USER_INPUT>>&type=etc
http://www.somedomain.com/folder/?someCmd=<<USER_INPUT>>&layer=etc
http://www.somedomain.com/folder/?itemId=<<USER_INPUT>>&value=etc
http://www.somedomain.com/folder/?pageR=<<USER_INPUT>>&caption=etc

So where "?" there are 4 different values, and where "&" there are also 4 completely different values.

EDIT 2
Ok, as per John's reply... I've tweaked it a little. How does it look? Just a rubbish as my first attempt at altering code?

var processForm = function(){
var value = $('#imageName').val(),
    outputElement = $('#icdnResults'),
    html = '',
    s_imageTag = function(size){
        return size + value;
    },

    e_imageTag = function(size2){
        return size2 + "\n";
    },

   size = ['s_catThumb', 's_productMain'], 
   size2 = ['e_catThumb', 'e_productMain'];

html += s_imageTag('s_catThumb ');
html += e_imageTag(' e_catThumb');
html += s_imageTag('s_productMain '); 
html += e_imageTag(' e_productMain'); 

outputElement.val(html);
};

$(function(){
$('#gen').on('click', processForm);
});
Alex
  • 41
  • 7

2 Answers2

1

Maybe this sort of thing?

http://jsfiddle.net/nvLx9/2/

HTML

<input id="user_input" type="text" placeholder="User Input" value="test">
<button id="process" type="button">Process</button>
<br>
<textarea id="output" row="4" cols="60" style="height:60px"></textarea>

<div id="images">
</div>

JS

var getLinks = function(value){
        var links = [
                'http://placehold.it/100x100/ff0000&text=<<USER_INPUT>>',
                'http://placehold.it/100x100/0000ff&text=<<USER_INPUT>>',
                'http://placehold.it/100x100/00ff00&text=<<USER_INPUT>>',
                'http://placehold.it/100x100/ff00ff&text=<<USER_INPUT>>',
            ];

            $.each(links, function(idx, link){
                links[idx] = link.replace('<<USER_INPUT>>', value);
            });

            return links;
    },
    processForm = function(){
        var value = $('#user_input').val(),
            links = getLinks(value),
            getText = function(){
                var h = '';
                $.each(links, function(idx, link){
                    h += link + "\n";
                });
                return h;
            },
            addImages = function(){
                var h = '';

                $.each(links, function(idx, link){
                    h += '<img src="'+link+'">';
                });

                $('#images').html(h);
            };

        $('#output').val(getText());
        addImages();
    };

$('#process').on('click', processForm);
John
  • 11
  • 2
  • Hi John, thanks for the reply to my question. first off, my apologies - I didn't ask my question properly. I have just updated it. Because the prefix and suffix have 4 different values each, would I be right in thinking that I'd have to create a new function? so... `imageTag2 = function(size2) {define all the values}` and then `html +=imageTag('Cat Thumb'); + imageTag2('Cat Thumb suffix')`? or am I making no sense at all – Alex Nov 07 '13 at 12:43
1

As above but without the use of an additional library. JQuery is great and if you are going to be doing a lot of JavaScript you may find it easier to work with. But if you would rather not add a dependency on an additional library the same can be done using vanilla JS:

http://jsfiddle.net/4GtFe/1/

HTML

<form name="invalidateForm" action="">Image Name:<br />
    <input id="imageName" type="text" name="imageName" value=""><br />
    <input class="btn" type="button" value="Generate URLs" id="gen">
    <input class="btn" type="reset"><br />
    <textarea id="icdnResults"></textarea>
</form>

JS

var processForm = function () {
    var value = document.getElementById('imageName').value,
        html = '',
        imageTag = function (size) {
            return 'prefix ' + size + ' <<' + value + '>> suffix ' + size + "\n";
        },
        sizes = ['text', 'text 2', 'text 3'];


    for (var i = 0; i < sizes.length; i++) {
        html += imageTag(sizes[i]);
    }

    document.getElementById('icdnResults').value = html;
};

document.getElementById('gen').addEventListener('click', function() {
    processForm();
}, false);

As shown in both my answer and the answer above; it is good practice to use unobtrusive javascript where possible. This will keep your code clean and improves readability and maintainability.

Additionally if you wish to support Internet Explorer 8 and older you will need to replace addEventListener with a function to handle it's support, see this post addEventListener in Internet Explorer.

Community
  • 1
  • 1
Jonathan
  • 1,833
  • 13
  • 15
  • Thanks for the code example and information about unobtrusive javascript - one to read up on, onced I have a better basic understanding. The page will only be used in Chrome, so no issues with IE. Thanks again Jonathan! – Alex Nov 07 '13 at 12:50
  • 1
    Alex I have reworked my [JSFiddle](http://jsfiddle.net/4GtFe/2/) to match your amended question. Is this any better? – Jonathan Nov 07 '13 at 17:29