Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Выборка Select (https://javascript.ru/forum/misc/27736-vyborka-select.html)

nike90 23.04.2012 11:28

Выборка Select
 
Подскажите пожалуйста как организовать выборку (именно) на JS выбранного option, мне нужно в переменную (к примеру author) - занести значение value="" выбранного option.
<select name="authors" id="authors">
<option value="1">текст 1</option>
<option value="3">текст 2</option>
<option value="3">текст 3</option>
<option value="4">текст 4</option>
</select>

devote 23.04.2012 11:46

var author = document.getElementById( 'authors' ).value;

nike90 23.04.2012 12:00

У меня такая конструкция выбирает первое значение которое изначально стоит первым в selecte, объясню зачем оно мне нужно. Я думаю много кто сталкивался с Fancy Uploader-ом я хочу добавить свой SELECT и в скрипте Fancy записывать в переменную значение выбраное в select, но сколько не пробывал JS выборку все время почему то выбирвется только первое поле, если нужно я выложу весь код. В чем может быть проблема?

devote 23.04.2012 12:01

выкладывайте код, ибо данный мною пример обязан выдавать значение именно выбранного пункта.

nike90 23.04.2012 12:20

window.addEvent('domready', function() { // wait for the content
    // ВЫБОРКА 
    var author = document.getElementById( 'authors' ).value; // она выбирает только почемуто 1е значение
    
    var up = new FancyUpload2($('demo-status'), $('demo-list'), { // options object
		// we console.log infos, remove that in production!!
		verbose: false,
		data: {'author':'author (вот сюда нужно вставить выбраное значение в Selecte)'}, 
		// url is read from the form, so you just have to change one place
		url: $('form-demo').action,
		
		// path to the SWF file
		path: 'source/Swiff.Uploader.swf',
		
		// remove that line to select all files, or edit it, add more items
		typeFilter: {
			'Изображения (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'
		},
		
		// this is our browse button, *target* is overlayed with the Flash movie
		target: 'demo-browse',
		
		// graceful degradation, onLoad is only called if all went well with Flash
		onLoad: function() {
			$('demo-status').removeClass('hide'); // we show the actual UI
			$('demo-fallback').destroy(); // ... and hide the plain form
			
			// We relay the interactions with the overlayed flash to the link
			this.target.addEvents({
				click: function() {
					return false;
				},
				mouseenter: function() {
					this.addClass('hover');
				},
				mouseleave: function() {
					this.removeClass('hover');
					this.blur();
				},
				mousedown: function() {
					this.focus();
				}
			});

			// Interactions for the 2 other buttons
			
			$('demo-clear').addEvent('click', function() {
				up.remove(); // remove all files
				return false;
			});

			$('demo-upload').addEvent('click', function() {
				up.start(); // start upload
				return false;
			});
		},
		
		// Edit the following lines, it is your custom event handling
		
		/**
		 * Is called when files were not added, "files" is an array of invalid File classes.
		 * 
		 * This example creates a list of error elements directly in the file list, which
		 * hide on click.
		 */ 
		onSelectFail: function(files) {
			files.each(function(file) {
				new Element('li', {
					'class': 'validation-error',
					html: file.validationErrorMessage || file.validationError,
					title: MooTools.lang.get('FancyUpload', 'removeTitle'),
					events: {
						click: function() {
							this.destroy();
						}
					}
				}).inject(this.list, 'top');
			}, this);
		},
		
		/**
		 * This one was directly in FancyUpload2 before, the event makes it
		 * easier for you, to add your own response handling (you probably want
		 * to send something else than JSON or different items).
		 */
		onFileSuccess: function(file, response) {
			var json = new Hash(JSON.decode(response, true) || {});
			
			if (json.get('status') == '1') {
				file.element.addClass('file-success');
				file.info.set('html', '<strong>Информация о файле:</strong> ' + json.get('width') + ' x ' + json.get('height') + 'px<br>Новое имя файла: ' + json.get('new') + '');
			} else {
				file.element.addClass('file-failed');
				file.info.set('html', '<strong>Ошибка:</strong> ' + json.get('error'));
			}
		},
		
		/**
		 * onFail is called when the Flash movie got bashed by some browser plugin
		 * like Adblock or Flashblock.
		 */
		onFail: function(error) {
			switch (error) {
				case 'hidden': // works after enabling the movie and clicking refresh
					alert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).');
					break;
				case 'blocked': // This no *full* fail, it works after the user clicks the button
					alert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).');
					break;
				case 'empty': // Oh oh, wrong path
					alert('A required file was not found, please be patient and we fix this.');
					break;
				case 'flash': // no flash 9+ :(
					alert('To enable the embedded uploader, install the latest Adobe Flash plugin.')
			}
		}
		
	});
	
});

nike90 23.04.2012 12:21

просто сам Fancy Uploader использует Mootools а я его не знаю вот решил все это дело сделать на JS

devote 23.04.2012 12:40

ну вы же где-то вызываете экземпляр up
вот перед вызовом добавьте строчку:
up.setOptions( { data: { author: document.getElementById( 'authors' ).value } } );
я мутулз честно говоря не особо знаю, а этот аплоадер тем более... но судя по коду примерно так.

nike90 23.04.2012 13:05

devote - я привел весь код который обрабатывает форму Fancy Upload - вот только не пойму куда притулить
up.setOptions( { data: { author: document.getElementById( 'authors' ).value } } );
- посмотри по коду и подскажы пожайлуйста

devote 23.04.2012 14:15

попробуйте добавить метод:
onStart: function() {
    this.setOptions( { data: { author: document.getElementById( 'authors' ).value } } );
}
но опять же говорю, это метод тыка.. так как я не знаю этой библиотеки.

nike90 23.04.2012 16:57

devote - абсолютно без результатно, заментил одну закономерность если я в поле <option ...> ставлю selected (<option selected ...>) то оно выбирает именно его. Помоги написать код на JS - логика такова, когда чел выбирает определенный option то ему ставится приставка selected

nike90 23.04.2012 17:00

можно даже его в форму поместить типа так - onChange=" сюда код написать присвоения selected"

nike90 23.04.2012 17:02

devote,
можно даже код написать в свойстве onChange = " код присвоения selected ", я думаю это решит проблему...


Часовой пояс GMT +3, время: 03:20.