doubi3929 2015-09-25 11:35
浏览 87
已采纳

在javascript生成的表单中创建输入字段

js Fiddle

I have a drop zone on a page which shows photos successfully uploaded to server once they are added to the drop zone. each photo has a class called uploaded holding each separate photo inside of it. Once the image is uploaded I need each photo to have an input field showing next to it allowing a user to add tags to each photo. Once they type tags which will be comma delimited in the input field they will be able to click submit. At that point the function called

addTags()

will be called and the tags will be added to the photo based on the file name. I am having trouble figuring out the most professional way to do this,

I was thinking of creating a form with all hidden fields adding the name of the field with a value holding the file name. This would be easy to obtain the file name and tags with ajax. Please show me how something like this would be done professionally.

This is the JS which allows and loops through showing the uploaded files,

 // Initialize the jQuery File Upload plugin
    $('#upload').fileupload({

        // This element will accept file drag/drop uploading
        dropZone: $('#drop'),

        // This function is called when a file is added to the queue;
        // either via the browse button, or via drag/drop:
        add: function (e, data) {

            var tpl = $('<li class="working uploaded"><input type="text" value="0" data-width="48" data-height="48"'+
                ' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');

        // Append the file name and file size      
            tpl.find('p').text(data.files[0].name)
                         .append('<i>' + formatFileSize(data.files[0].size) + '</i>');

            // Add the HTML to the UL element
            data.context = tpl.appendTo(ul);

            // Initialize the knob plugin
            tpl.find('input').knob();

            // Listen for clicks on the cancel icon
            tpl.find('span').click(function(){

                if(tpl.hasClass('working')){
                    jqXHR.abort();
                }

                tpl.fadeOut(function(){
                    tpl.remove();
                });

            });

            // Automatically upload the file once it is added to the queue
            var jqXHR = data.submit();
        },

So the filename is returned for each file that is uploaded in the drop zone like this,

tpl.find('p').text(data.files[0].name)

Now how would I create form in this JS function adding the name to each hidden form field for each file uploaded and add a text input field allowing entry of tags for the pictures.

essentially i'm looking for a way to add a form like this,

 <form onSubmit="addTags();return false;">
<input type="hidden" name="imgName" value="var imgName" id="imgName">
<input type="text" name="tags" palceholder="add tags seperated by ," id="tags">
<input type="submit" name="login" value="Add Tags" class="submit" id="adTags"/>
                    </form>

addTags() function

function addTags(){
    $.ajax({
        type: 'POST',
        url: 'data/add_tags.php',
        data: "&tag_type_id=" + $('#tag_type_id').val() + "&tag_target_name=" + $('#tag_target_name').val() +
            "&tag_target_url=" + $('#tag_target_url').val() + "&tags=" + $('#tags').val(),    
                success: function(response){
            console.log(response);
            if(response === 'error'){
                        $('.messageText').empty()
                    $('.messageImage').empty()
                    $('.messageText').append('Please add tags seperated by commas');
                $(".messageImage").append('<img src="images/error.png" height="50" width="50">');
                $('.message').slideDown(400).delay(10000).fadeOut(400)   
            }
            else {
                    $('.messageText').empty()
                    $('.messageImage').empty()
                    $('.messageText').append('Your tags have been added.');
                    $(".messageImage").append('<img src="images/success.png" height="50" width="50">');
                    $('.message').slideDown(400).delay(10000).fadeOut(400)   
            }   
       }
    });
 };

   AJAX makes call to this php function,

<?php
//Include files                 
require_once('../classes/class_login.php');

$tag_type_id = $_POST['tag_type_id'];
$tag_target_name = $_POST['tag_target_name'];
$tag_target_url = $_POST['tag_target_url'];
$tags = $_POST['tags'];

    /*** begin with some validation ***/
    if(!isset($_POST['tag_type_id'], $_POST['tag_target_name'], $_POST['tag_target_url'], $_POST['tags']))
    {
        /*** if no POST is submited ***/
        $msg = 'Please Submit a tag';
        print('error');
    }
    elseif(filter_var($_POST['tag_type_id'], FILTER_VALIDATE_INT, array("min_range"=>1, "max_range"=>100)) == false)
    {
        /*** if tag is too short ***/
        $msg = 'Invalid Tag Type';
                print('error');
    }
    elseif( strlen($_POST['tag_target_url']) == 0 )
    {
        /*** if tag is too long ***/
        $msg = 'Tag target is required';
                print('error');
    }
    elseif( strlen($_POST['tags']) == 0 )
    {
        $msg = 'Tag Required';
                print('error');
    }
    elseif(  strlen($_POST['tag_target_name']) == 0 )
    {
        $msg = 'Tag Name is too short';
                print('error');
    }
    elseif( strlen($_POST['tag_target_name']) > 30 )
    {
        $msg = 'Tag Name is too long!';
                print('error');
    }
    else
    {
        /*** if we are here, all is well ***/

        $tag_type_id = filter_var($_POST['tag_type_id'], FILTER_SANITIZE_NUMBER_INT);
        $tag_target_url = filter_var($_POST['tag_target_url'], FILTER_SANITIZE_STRING);
        $tag_target_name = filter_var($_POST['tag_target_name'], FILTER_SANITIZE_STRING);
        $tags = filter_var($_POST['tags'], FILTER_SANITIZE_STRING);

            addTags($tag_type_id, $tag_target_name, $tag_target_url, $tags);

            $msg = 'Tag Type Added!';
                    print('success');
        }

?>       

php function is defined in a class like this,

function addTags($tag_type_id, $tag_target_name, $tag_target_url, $tags){

        /*** explode the tag string ***/
            $tag_array = explode(',', $tags);

            /*** loop of the tags array ***/
            foreach( $tag_array as $tag_name )
            {
                /*** insert tag into tags table ***/
                $tag_name = strtolower(trim($tag_name));

                $databaseQuery = "INSERT IGNORE INTO tags (tag_name ) VALUES ('$tag_name')";
                //Execute database query
                executeDatabase($databaseQuery);

                /*** get the tag ID from the db ***/
                $databaseQuery  = "SELECT tag_id FROM tags WHERE tag_name='$tag_name'";
                $result = executeDatabase($databaseQuery);
                $tag_id = mysqli_num_rows($result);

                /*** now insert the target ***/
                $databaseQuery = "INSERT INTO tag_targets
                    (tag_id, tag_target_name, tag_target_url, tag_type_id)
                    VALUES
                    ('$tag_id', '$tag_target_name', '$tag_target_url', '$tag_type_id')";
                executeDatabase($databaseQuery);
            }
}
  • 写回答

1条回答 默认 最新

  • dongre6073 2015-09-25 12:20
    关注

    In your loop, you can create elements, set their attributes and append them to the DOM using createElement, setAttribute, and appendChild. Example:

    var myNewElement= document.createElement("input");
    myNewElement.setAttribute("id","new_element_id");
    myNewElement.setAttribute("class","new_element_class");
    myNewElement.setAttribute("name","new_element_name");
    document.getElementById("desired_parent").appendChild(myNewElement);
    

    Note that there is an alternative/complementary method to this. If you're creating a lot of similar, complex elements (e.g. you have an 'image descriptor' box that has some text elements, the input field, a few divs, etc.), you can have a hidden element on the page with all those elements, clone it, and use this method to modify part of it and put it where you want.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿